Scala学习笔记(3)-表达式归纳
语法:使用表达式定义值和变量
val <identifier>[:<type>]=<expression> 字面值类型
var <identifier>[:<type>]=<expression> 变量类型
实例1:
同一级定义类型
scala> val x=5*20;val amount=x+10
x: Int = 100
amount: Int = 110
块局部定义(建议采用)
scala> val amount={val x=5*20;x+10}
amount: Int = 110
写法2:
scala> val amount={
| val x=5*20
| x+10
| }
amount: Int = 110
表达式嵌套:
scala> {val a=1;{val b=a*2;{val c=b+4;c}}}
res11: Int = 6
实例2-if-else:
if(<Boolean expression>)<expression>
else <expression>
scala> if(47%3 >0) print("not a multipul of 3")
scala> val result=if(false) "what does this return?"
result: Any = () //未定类型,可能是String或Unit
scala> val x=10;val y=20
x: Int = 10
y: Int = 20
scala> val max=if(x>y)x else y
max: Int = 20
匹配表达式(类似的Switch表达式)
<expression> match{
case <pattern match>=><expression>
}