2025/1/29


Scala的语法比Python更严格,但功能强大。掌握基础语法是编写复杂程序的第一步。
变量:使用val(不可变变量)和var(可变变量)。
数据类型:包括数字、字符串、元组、列表等。
控制流:包括条件语句(if)和循环语句(for、while)。
示例代码:

 

// 数据类型
val number: Int = 42
val name: String = "Alice"
val point: (Int, Int) = (1, 2)
val fruits: List[String] = List("apple", "banana", "cherry")

// 条件语句
if (number > 40) {
println("Number is greater than 40")
} else {
println("Number is less than or equal to 40")
}

// for循环
for (fruit <- fruits) {
println(fruit)
}

// while循环
var count = 0
while (count < 5) {
println(count)
count += 1
}

 

运行步骤:
在src/main/scala/目录下创建一个文件,例如BasicSyntax.scala。
将上述代码粘贴到文件中。
在项目根目录下运行:

sbt run

posted @ 2025-01-29 21:08  伐木工熊大  阅读(19)  评论(0)    收藏  举报