一、if 表达式
### --- if表达式
~~~ Scala中 if 表达式有返回值。
~~~ 如果if 和 else 的返回值类型不一样,那么就返回两个返回值类型公共的父类。
### --- 编程示例
~~~ # if 语句有返回值
val x = 10
val s = if (x > 0)
1
else
-1
~~~ # 多分支if 语句
val s = if (x==0)
0
else if (x > 1)
1
else
0
~~~ # 如果返回的类型不一致就返回公共的父类
val s = if (x > 0)
"positive"
else
-1
~~~ # 缺省 else 语句;s1/s2的返回类型不同
val s1 = if (x > 0) 1 等价 val s1 = if (x > 0) 1 else ()
val s2 = if (x > 0) "positive" 等价 val s2 = if (x > 0) "positive" else
()
### --- 编程代码
package yanqi.cn.part02
object IfDemo {
def main(args: Array[String]): Unit = {
//在Scala中不需要添加分号作为语句块的结束符
val num = 20
//在Scala中 if else语句是有返回值的,返回值就是最后一条语句的返回值
if (num > 20) "zhangsan" else "jacky"
//if语句可以嵌套
if (num < 20)
0
else if (num == 20)
1
else
-1
//因为if else语句是有返回值的,所以可以直接将if else语句赋值给一个变量
//注意:返回值不需加return关键字
val result = if (num > 20) "zhangsan" else "jacky"
//如果if else语句中返回值的类型不一样,那么Scala会自动推断出两者的公共父类型,作为表达式的返回值类开型
val result2: Any = if (num == 20) "jacky" else 100
println(result2)
//如果if else语句中缺省了else语句块,那么默认else的值是Unit
//Unit用“()”来表示,类似于Java中的void
val result3 = if (num > 20) "jacky"
val result4 = if (num > 20) "jacky" else ()
}
}
### --- 编译打印
D:\JAVA\jdk1.8.0_231\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=52540:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath D:\JAVA\jdk1.8.0_231\jre\lib\charsets.jar;D:\JAVA\jdk1.8.0_231\jre\lib\deploy.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\dnsns.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\jaccess.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\localedata.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\nashorn.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunec.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\zipfs.jar;D:\JAVA\jdk1.8.0_231\jre\lib\javaws.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jce.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jfr.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jfxswt.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jsse.jar;D:\JAVA\jdk1.8.0_231\jre\lib\management-agent.jar;D:\JAVA\jdk1.8.0_231\jre\lib\plugin.jar;D:\JAVA\jdk1.8.0_231\jre\lib\resources.jar;D:\JAVA\jdk1.8.0_231\jre\lib\rt.jar;E:\NO.Z.10000——javaproject\NO.Z.00002.Hadoop\ScalaPro\out\production\ScalaPro;D:\JAVA\scala-2.12.2\lib\scala-library.jar;D:\JAVA\scala-2.12.2\lib\scala-reflect.jar yanqi.cn.part02.IfDemo
jacky
Process finished with exit code 0