Scala 基础语法学习笔记
变量与常量
var a = 10
val b = "hello"
数据类型
val a: Int = 10
val b: Double = 3.14
val c: String = "hello world"
数组
val arr = Array(1, 2, 3)
val first = arr(0)
for (i <- arr) {
println(i)
}
条件语句
if (a > 10) {
println("a大于10")
} else {
println("a小于等于10")
}
val day = "Monday"
day match {
case "Monday" => println("星期一")
case "Tuesday" => println("星期二")
case _ => println("其他")
}
循环语句
for (i <- 1 to 10) {
println(i)
}
while (a < 20) {
println(a)
a += 1
}
函数
def add(a: Int, b: Int): Int = {
a + b
}
def printHello(): Unit = {
println("hello")
}
类与对象
class Person(name: String, age: Int) {
def printInfo(): Unit = {
println(s"姓名: $name 年龄: $age")
}
}
val p = new Person("Tom", 20)
p.printInfo()