0Pricing
Scala for Backend Engineering & Functional Programming · 강의

val과 var

변경할 수 없는 바인딩과 변경 가능한 바인딩을 배워 보세요.

val과 var은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Two Ways to Name Values

In Scala, you bind a name to a value using either val or var.

val creates an immutable binding: once assigned, it can never point to another value. var creates a mutable binding that you can reassign later.

Choosing between them is one of the first habits a Scala backend engineer builds.

val name = "Ada"
var score = 10

Defining a val

A val is read-only. You assign it once, and the compiler guarantees it stays the same.

This makes your code easier to reason about: a val never surprises you with a changed value somewhere else.

object Main extends App {
  val pi = 3.14
  println(pi)
}

Reassigning a val Fails

Trying to reassign a val is a compile error, not a runtime crash. The compiler stops you before the program ever runs.

The snippet below would fail with reassignment to val.

val country = "Turkey"
country = "Spain" // error: reassignment to val

Defining a var

A var can be reassigned as many times as you like, as long as the new value has a compatible type.

Use var when a value genuinely needs to change over time, such as a counter in a loop.

object Main extends App {
  var count = 0
  count = count + 1
  count = count + 1
  println(count)
}

var Keeps Its Type

Even though a var can be reassigned, its type is fixed at definition.

If level starts as an Int, you cannot later store a String in it. The compiler rejects the mismatch.

var level = 1
level = 5        // ok, still an Int
level = "high"  // error: type mismatch

Prefer val by Default

Idiomatic Scala favors val almost everywhere. Immutability avoids whole classes of bugs and makes concurrent code safer.

  • Reach for val first.
  • Switch to var only when you truly need mutation.

Rewriting var as val

Many loops that look like they need a var can be expressed with a val and an expression instead.

Here a sum is computed with a range and sum, no mutation required.

object Main extends App {
  val total = (1 to 5).sum
  println(total)
}

Scope of a Binding

Both val and var live inside the block { ... } where they are defined.

A binding declared inside a block is not visible outside of it. This keeps names tidy and prevents accidental reuse.

object Main extends App {
  val outer = 1
  {
    val inner = 2
    println(outer + inner)
  }
  // inner is not visible here
}

Lazy val

A lazy val is computed only the first time it is used, then cached.

This is handy for expensive values you might not always need. The body runs at most once.

object Main extends App {
  lazy val greeting = { println("computing"); "Hi" }
  println("before")
  println(greeting)
  println(greeting)
}

val with Explicit Type

You can annotate a binding's type after a colon. This documents intent and can widen the type on purpose.

Here amount is declared as a Double even though 10 looks like an Int.

val amount: Double = 10
val label: String = "price"

val vs var Side by Side

The two behave the same until you try to reassign.

  • val x: assign once, fixed forever.
  • var y: assign and reassign freely.

The program below increments only the var.

object Main extends App {
  val base = 100
  var bonus = 0
  bonus = bonus + 25
  println(base + bonus)
}

Quick Check

Test your understanding of val and var.

Recap

You learned the two ways to bind names in Scala.

  • val is immutable and is the default choice.
  • var is mutable and reserved for values that must change.
  • Reassigning a val is a compile error.
  • Types are fixed for both; lazy val defers computation.

자주 묻는 질문

“val과 var” 강의는 무료인가요?

네 — “val과 var” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“val과 var”에서 뭘 배우나요?

변경할 수 없는 바인딩과 변경 가능한 바인딩을 배워 보세요. 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“val과 var” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. val과 var
  2. 기본 형식과 리터럴
  3. 형식 추론
  4. 문보다 식
← Scala for Backend Engineering & Functional Programming(으)로 돌아가기