Scala教程
Scala面向对象
Scala高级

Scala 条件表达式

Scala 条件表达式

Scala 提供 if 语句来测试条件表达式。它测试布尔条件表达式,它可以是真或假。 Scala 使用各种类型的 if else 语句。
If 语句 If-else 语句 嵌套的 if-else 语句 If-else-if 阶梯语句

Scala if 语句

scala if 语句用于测试 scala 中的条件。仅当条件为真时才执行 if 块,否则跳过 if 块的执行。
语法
if(condition){
    // Statements to be executed
}

流程图

Scala If statement 1

Scala 示例: If 语句

var age:int = 20;
if(age > 18){
    println ("Age is greate than 18")
}
输出:
Age is greate than 18

Scala If-Else 语句

Scala if-else 语句测试条件。如果条件为真,则执行 if 块,否则执行 else 块。
语法
if(condition){
    // if block statements to be executed
} else {
    // else bock statements to be executed
}

流程图

Scala If statement 2

Scala if-else 示例

var number:int = 21
if(number%2==0){
    println("Even number")
}else{
    println("Odd number")
}
输出:
Odd number

Scala If-Else-If 梯形语句

Scala if-else-if 梯形执行多个条件语句中的一个条件。
语法
if (condition1){  
//Code to be executed if condition1 is true  
} else if (condition2){  
//Code to be executed if condition2 is true  
} else if (condition3){  
//Code to be executed if condition3 is true  
}  
...  
else {  
//Code to be executed if all the conditions are false  
}  

流程图

Scala If statement 3

Scala If-Else-If 梯形图示例

var number:int = 85
if(number>=0 && number<50){
    println ("fail")
}
else if(number>=50 && number<60){
    println("D Grade")
}
else if(number>=60 && number<70){
    println("C Grade")
}
else if(number>=70 && number<80){
    println("B Grade")
}
else if(number>=80 && number<90){
    println("A Grade")
}
else if(number>=90 && number<=100){
    println("A+ Grade")
}
else println ("Invalid")
输出:
A Grade

Scala If Statement 作为三元运算符的更好替代品

在 Scala 中,您可以将 if 语句结果分配给函数。 Scala 没有像 C/C++ 那样的三元运算符概念,但提供了更强大的 if 可以返回值。让我们看一个例子
例子
object MainObject {
   def main(args: Array[String]) {
      val result = checkIt(-10)
      println (result)
   }
    def checkIt (a:Int)  =  if (a >= 0) 1 else -1  // Passing a if expression value to function
}
输出:
    -1
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4