条件表达式
- if/else语句同Java和C++一样
- scala的if/else的表达式有值
if(x>0) 1 else -1
- 将表达式的结果赋值给变量
val s = if(x>0) 1 else -1
- scala中每个表达式都有一个类型,
if(x>0) 1 else -1
的类型是Int,因为两个分支的类型都是Int。对于混合类型表达式,分支的类型不一样,得到的类型是两个分支类型的超类型
.
val s = if(x>0) 1 else "None"
// s: Any = 1
val s = if(x>0) 1 else -1.0
// s: Double = 1.0
//如果只有一个分支
val s = if(x>0) 1
//s: AnyVal = 1
val s = if(x>0) "a"
//s: Any = a
val s:String = if(x>0) "add"
//<console>:12: error: type mismatch;
// found : Unit
// required: String
// val s:String = if(x>0) "add"
// ^
val s:String = if(x>0) "add" else "dfd"
// s: String = add
- Unit类型,只有一个值,即一对小括号
( )
,括号里可以加空格,也可以不加
val a:Unit=( )
// a: Unit = ()
a.getClass
// Class[Unit] = void
- 交互式的REPL中输入多行代码,先输入
:paste
回车,输入内容,结束后按下Ctrl+D
组合键结束键盘输入。
语句终止
- scala的每一行结尾不需要加分号。
- 如果一行写多条语句,每一条语句需要用分号分割。
- 每一行想写分号也可以写上,it depends you
块表达式和赋值
- 块语句,用大括号括起来的内容: { }
- 块的最后一个表达式的值就是块的值
- 赋值表达式的值是Unit类型,值的内容是
()
。
val k={
3>2}
// k: Boolean = true
val k={
var a=1;var b=2}
// k: Unit = ()
- 不要连续两次赋值,因为赋值表达式的值是Unit类型的,除非是确实想把Unit类型赋值给变量。
val y=x=1
// y: Unit = ()
x
//Int = 1
- 也不要同时初始化三个变量赋值
val a=b=c=1 //错误
// <console>:11: error: not found: value b
// val a=b=c=1
输入和输出
- 打印值用print或println。
- println会自动在后面追加换行
- C风格的printf函数
printf("Hello %s haha %d,%n","world",100)
// Hello world haha 100,
- 插值字符串,包括f字符串和s字符串
- f 字符串:被格式化的字符串以字母f开头,包含以$开头,并且可能带有 C风格的格式化字符串的表达式
val name = "Sam";val age =12
print(f"Hello,$name! In six months, you will be ${age + 0.5}%7.2f years old.%n")
//Hello,Sam! In six months, you will be 12.50 years old.
- s 字符串:字符串可以包含表达式,但不能格式化。比f字符串少了格式化功能。
print(s"Hello,${"Bargins"}! In six months, you will be ${var age =93;age+0.5} years old.")
//Hello,Bargins! In six months, you will be 93.5 years old.
- 从控制台输入scala.io.StdIn的readLine方法读取一行。此外还有读取特定类型的值。
r