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

基本语法与类型

了解 Scala 的基础语法、变量声明(val/var)、常见数据类型和基本运算符。

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

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

Scala's Clean Syntax

Welcome to Scala's basic syntax! Scala is designed to be concise and expressive, often allowing you to write less code to achieve more.

Unlike some languages, semicolons are usually optional at the end of a line if there's only one statement. This helps keep your code clean.

Expressions Are Key

In Scala, almost everything is an expression, meaning it evaluates to a value. This is a powerful concept that makes your code more functional and predictable.

Even a simple calculation or a conditional block can return a value.

Try running this example:

object Main {
  def main(args: Array[String]): Unit = {
    val x = 5 + 3
    println(s"The value of x is: $x")

    val message = if (x > 7) "Greater than 7" else "Not greater than 7"
    println(message)
  }
}

`val`: Immutable Values

When you declare a variable using val, you are creating an immutable value. This means once it's assigned, its value cannot be changed.

Immutability is a cornerstone of functional programming and helps prevent unexpected side effects, making your code safer and easier to reason about.

Try it out:

object Main {
  def main(args: Array[String]): Unit = {
    val greeting = "Hello, Coddy!"
    println(greeting)
    // greeting = "New message" // This would cause a compile error!
  }
}

`var`: Mutable Variables

Sometimes you need a variable whose value can change. For this, Scala provides var for mutable variables.

While useful, it's a good practice in Scala to favor val over var whenever possible to embrace immutability and functional style.

See how `var` works:

object Main {
  def main(args: Array[String]): Unit = {
    var counter = 0
    println(s"Initial counter: $counter")
    counter = counter + 1
    println(s"New counter: $counter")
  }
}

Numbers: Int, Long, Double

Scala supports common numeric types. The compiler often infers the type, but you can specify it.

  • Int: For whole numbers (e.g., 10)
  • Long: For larger whole numbers (suffix L, e.g., 10000000000L)
  • Double: For floating-point numbers (decimals, e.g., 3.14)

Here's an example:

object Main {
  def main(args: Array[String]): Unit = {
    val anInt = 42
    val aLong = 1234567890123L
    val aDouble = 3.14159

    println(s"Int: $anInt")
    println(s"Long: $aLong")
    println(s"Double: $aDouble")
  }
}

Boolean and Char Types

Beyond numbers, Scala has types for truth values and single characters:

  • Boolean: Represents truth values, either true or false.
  • Char: Stores a single character, enclosed in single quotes (e.g., 'A').

These are fundamental for logic and text processing.

Example:

object Main {
  def main(args: Array[String]): Unit = {
    val isActive = true
    val initial = 'C'

    println(s"Is active? $isActive")
    println(s"Initial character: $initial")
  }
}

Strings and Text

The String type is used for sequences of characters, or text. Strings are immutable in Scala, just like in Java.

A very useful feature is String Interpolation, which allows you to embed expressions directly within string literals using an s prefix and $ for variables.

Check this out:

object Main {
  def main(args: Array[String]): Unit = {
    val name = "Coddy"
    val age = 3

    val greeting = s"Hello, my name is $name and I am $age years old."
    println(greeting)

    val mathResult = s"Two plus two is ${2 + 2}"
    println(mathResult)
  }
}

Basic Arithmetic Operators

Scala provides standard arithmetic operators for performing calculations with numbers:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulo - remainder of division)

These operators work as you'd expect, returning a new numeric value.

Let's do some math:

object Main {
  def main(args: Array[String]): Unit = {
    val a = 10
    val b = 3

    println(s"Addition: ${a + b}")
    println(s"Subtraction: ${a - b}")
    println(s"Multiplication: ${a * b}")
    println(s"Division: ${a / b} (integer division)")
    println(s"Modulo: ${a % b}")

    val c = 10.0
    val d = 3.0
    println(s"Float Division: ${c / d}")
  }
}

Comparison Operators

Comparison operators are used to compare two values and always return a Boolean (true or false).

  • == (Equal to)
  • != (Not equal to)
  • < (Less than)
  • > (Greater than)
  • <= (Less than or equal to)
  • >= (Greater than or equal to)

They are essential for control flow and decision-making.

object Main {
  def main(args: Array[String]): Unit = {
    val x = 10
    val y = 5

    println(s"x == y: ${x == y}")
    println(s"x != y: ${x != y}")
    println(s"x > y: ${x > y}")
    println(s"x <= y: ${x <= y}")
  }
}

Quick Check: Variables & Operators

Consider the following Scala code snippet:

object Main {
  def main(args: Array[String]): Unit = {
    val num1 = 7
    var num2 = 3
    num2 = num1 * 2
    val finalResult = num1 + num2 - 5
    println(finalResult)
  }
}

Recap: Syntax & Types

Great job! In this lesson, you've learned the fundamentals of Scala's basic syntax, including the use of expressions and the optional nature of semicolons.

We explored how to declare variables using val for immutable values and var for mutable ones. You also got familiar with common data types like Int, Long, Double, Boolean, Char, and String, including handy String Interpolation.

Finally, you practiced using basic arithmetic and comparison operators to perform calculations and logical checks. Keep practicing these basics as they are the building blocks for more complex Scala programs!

常见问题解答

「基本语法与类型」课时是免费的吗?

是的 — 「基本语法与类型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 3 节课。

「基本语法与类型」这节课中我会学到什么?

了解 Scala 的基础语法、变量声明(val/var)、常见数据类型和基本运算符。 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「基本语法与类型」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. Scala 入门
  2. 基本语法与类型
  3. 控制结构与函数
← 返回 Scala for Backend Engineering & Functional Programming