0Pricing
Scala for Backend Engineering & Functional Programming · 课时

val、var 与类型

绑定与类型推断

val、var 与类型 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Bindings in Scala

In Scala you give names to values using bindings. The two keywords are val and var.

A val is immutable (it cannot be reassigned), while a var is mutable (it can be reassigned).

Declaring a val

A val binds a name to a value once. Trying to reassign it is a compile error.

Prefer val by default. Immutability makes code easier to reason about.

object Main {
  def main(args: Array[String]): Unit = {
    val name = "Ada"
    println(name)
  }
}

Declaring a var

A var can be reassigned with =. Use it only when you genuinely need mutable state.

Notice that the new value must still match the original type.

object Main {
  def main(args: Array[String]): Unit = {
    var count = 0
    count = count + 1
    count = count + 1
    println(count)
  }
}

Type Inference

Scala usually figures out the type for you. Writing val x = 42 makes x an Int automatically.

This is called type inference: you get static typing without always writing the type.

object Main {
  def main(args: Array[String]): Unit = {
    val x = 42
    val pi = 3.14
    val flag = true
    println(x)
    println(pi)
    println(flag)
  }
}

Explicit Type Annotations

You can also state the type explicitly after a colon: val x: Int = 42.

This is useful for documentation, or to choose a wider type than the one inferred.

object Main {
  def main(args: Array[String]): Unit = {
    val age: Int = 30
    val price: Double = 9.99
    val label: String = "Sale"
    println(label + ": " + price)
  }
}

Common Numeric Types

Scala has several numeric types:

  • Int for whole numbers
  • Long for big whole numbers
  • Double for decimals
  • Float for smaller decimals

An integer literal defaults to Int; a decimal literal defaults to Double.

object Main {
  def main(args: Array[String]): Unit = {
    val whole: Int = 7
    val big: Long = 9000000000L
    val dec: Double = 2.5
    println(whole + dec)
  }
}

Boolean and Char

Boolean holds true or false. Char holds a single character written in single quotes.

These are full-fledged types you can store in vals and vars.

object Main {
  def main(args: Array[String]): Unit = {
    val isReady: Boolean = true
    val grade: Char = 'A'
    println(isReady)
    println(grade)
  }
}

String Type

String holds text in double quotes. Strings are immutable in Scala.

You can concatenate them with + and call many useful methods on them.

object Main {
  def main(args: Array[String]): Unit = {
    val first = "Grace"
    val last = "Hopper"
    val full = first + " " + last
    println(full.toUpperCase)
  }
}

Why val Over var?

Immutable values prevent a whole class of bugs: nothing else can change them out from under you.

  • Easier to reason about
  • Safer in concurrent code
  • Encourages a functional style

Reach for var only when mutation is truly required.

Type Safety in Action

Because Scala is statically typed, the compiler catches type mismatches before the program runs.

Assigning text to an Int would fail at compile time. Here is valid, type-correct code.

object Main {
  def main(args: Array[String]): Unit = {
    val quantity: Int = 3
    val unitPrice: Double = 4.50
    val total: Double = quantity * unitPrice
    println(total)
  }
}

Putting It Together

Combine immutable and mutable bindings with inference and annotations in one small program.

Notice how the compiler tracks every type for you.

object Main {
  def main(args: Array[String]): Unit = {
    val base = 100
    var running = base
    val step: Int = 25
    running = running + step
    println(running)
  }
}

Quick Check

Check your understanding of bindings and types.

Recap

You learned how Scala names values:

  • val is an immutable binding; var is mutable
  • Type inference picks the type from the value
  • You can add explicit annotations like val x: Int
  • Core types include Int, Long, Double, Boolean, Char, and String
  • Prefer val for safer, clearer code

常见问题解答

「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 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「val、var 与类型」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?

能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 REPL
  2. val、var 与类型
  3. 表达式优于语句
  4. 字符串插值
← 返回 Scala for Backend Engineering & Functional Programming