val 与 var
不可变和可变绑定。
val 与 var 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 = 10Defining 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 valDefining 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 mismatchPrefer val by Default
Idiomatic Scala favors val almost everywhere. Immutability avoids whole classes of bugs and makes concurrent code safer.
- Reach for
valfirst. - Switch to
varonly 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.
valis immutable and is the default choice.varis mutable and reserved for values that must change.- Reassigning a
valis a compile error. - Types are fixed for both;
lazy valdefers computation.
常见问题解答
「val 与 var」课时是免费的吗?
是的 — 「val 与 var」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。
「val 与 var」这节课中我会学到什么?
不可变和可变绑定。 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「val 与 var」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?
能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- val 与 var
- 基本类型和字面量
- 类型推断
- 以表达式为主,而非语句