文章目录
- 1. var 变量,val常量
- 2. 分支、循环
- 3. 函数、方法
- 4. 闭包
学自 https://www.runoob.com/scala/scala-tutorial.html
1. var 变量,val常量
scala 语句 用 ; 或者 \n
分句
object HelloWorld { // 类名跟文件名一致def main(args: Array[String]):Unit = { // Unit 相当于 voidprintln("Hello World!")var myVar : String = "Foo"val myVal : String = "Too"myVar = "hello"// myVal = "world" // val 相当于常量,不能再次赋值val a, b, c = 100 // 不能分别赋值println(a,b,c) //(100,100,100)var pa = (40, "foo")println(pa) // (40,foo)
2. 分支、循环
- 跟 java、 c++ 很像
if(a < 200)println("a < 200")else if(a == 200)println("a == 200")elseprintln("a > 200")var n = 10while(n > 0){println(n)n -= 1}n = -1do{println(n)n -= 1}while(n > 0)for(x <- 1 to 10){println(x) // 包含结束的数}for(x <- 1 to 3; y <- 1 to 3){println(x, y) // 双重循环}var numList = List(100,2,3,4,5)for(a <- numList){println(a)}// 过滤元素for(a <- numList if a < 5; if a != 3){println(a)}// for yield : for 的返回值作为变量存储var returnVal = for{a <- numList if a < 5; if a != 3} yield afor(a <- returnVal)println(a)
- 特有的 break 方式
Breaks.breakable{}
import scala.util.control._val loop = new Breaksloop.breakable{for(a <- numList){println(a)if(a == 3)loop.break}}println("after break")
3. 函数、方法
// val 定义函数, def 定义方法class Test{def method(x:Int) = x + 3 // 多行语句,可用 = {。。。}val func = (x:Int) => x + 3}var obj = new Test()println(obj.method(2)) // 5println(obj.func(2)) // 5// 可变参数def printString(s : String*) = {for(si <- s)println(si)}printString("hello","michael","scala");//指定参数,默认参数def addInt(a:Int, b:Int=2, c:Int=3) : Int = {var sum = 0sum = a+b+cprintln(a,b,c)return sum}println(addInt(1)) // 6// 匿名函数var mul = (x:Int, y:Int) => x*yprintln(mul(3,4))var userDir = () => {System.getProperty("user.dir")}println(userDir())// 偏应用函数是一种表达式,你不需要提供函数需要的所有参数// 只需要提供部分,或不提供所需参数import java.util.Datedef log(date : Date, message : String) = {println(date + "-----" + message)}val date = new Dateval logWithDateBound = log(date, _ : String)logWithDateBound("message1")Thread.sleep(1000)logWithDateBound("message2")Thread.sleep(1000)logWithDateBound("message3")
4. 闭包
// 闭包var factor = 3val multi = (i : Int) => i*factorprintln(multi(5)) // 15factor = 2println(multi(5)) // 10}
}