Scala是一种结合了面向对象和函数式编程特性的多范式语言,运行在JVM上。以下是Scala的主要语法要点:
1. 变量声明
// 不可变变量(推荐) val name: String = "Alice" // 显式类型声明 val age = 25 // 类型推断 // 可变变量 var count: Int = 0 count += 1
2. 基本数据类型
Scala的所有类型都是对象,没有原始类型:
val b: Byte = 1 val i: Int = 123 val l: Long = 123456789L val f: Float = 3.14f val d: Double = 3.14 val c: Char = 'A' val bool: Boolean = true val s: String = "Hello"
3. 函数定义
// 方法定义 def add(x: Int, y: Int): Int = { x + y } // 简写形式 def multiply(x: Int, y: Int) = x * y // 无参函数 def greet(): Unit = println("Hello!") // 高阶函数 def applyFunc(f: Int => Int, x: Int) = f(x)
4. 控制结构
// if-else表达式(有返回值) val max = if (a > b) a else b // while循环 while (condition) { // 代码 } // for表达式 for (i <- 1 to 5) println(i) // 1到5 for (i <- 1 until 5) println(i) // 1到4 // 带条件的for for { i <- 1 to 3 j <- 1 to 3 if i == j } println(s"($i, $j)") // for推导式(yield) val squares = for (i <- 1 to 5) yield i * i
5. 集合
// 列表(List) val nums = List(1, 2, 3) val doubled = nums.map(_ * 2) // 集(Set) val unique = Set(1, 2, 2, 3) // Set(1, 2, 3) // 映射(Map) val ages = Map("Alice" -> 25, "Bob" -> 30) val aliceAge = ages("Alice") // 元组(Tuple) val pair = (1, "one") println(pair._1) // 1 println(pair._2) // "one"
6. 类和对象
// 类定义 class Person(val name: String, var age: Int) { // 方法 def greet(): String = s"Hello, I'm $name" // 重写toString override def toString = s"Person($name, $age)" } // 创建实例 val p = new Person("Alice", 25) println(p.name) // Alice p.age = 26 // 可变字段 // 单例对象 object Logger { def log(message: String): Unit = println(s"LOG: $message") } Logger.log("Starting app")
7. 模式匹配
val x: Any = 123 x match { case i: Int => println("整数") case s: String => println("字符串") case _ => println("其他") } // case类匹配 case class Point(x: Int, y: Int) val p = Point(1, 2) p match { case Point(0, 0) => println("原点") case Point(x, 0) => println(s"x轴上的点$x") case _ => println("其他位置") }
8. 特质(Trait)
类似Java的接口,但可以有实现:
trait Greeter { def greet(name: String): Unit def defaultGreet(): Unit = println("Hello!") } class FriendlyGreeter extends Greeter { def greet(name: String) = println(s"Hello, $name!") }
9. 隐式转换
implicit def intToString(x: Int): String = x.toString def printString(s: String) = println(s) printString(123) // 自动调用intToString
10. 未来和并发
import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global val f = Future { // 异步计算 Thread.sleep(1000) 42 } f.onComplete { case Success(value) => println(s"Got $value") case Failure(e) => println(s"Error: $e") }
Scala还有更多高级特性如类型参数、协变/逆变、宏等,这些是基础语法要点。