Kotlin學習筆記-----if和when


條件控制

if條件判斷

if的使用和java里面一樣

// Java中的if
int score = 90;
if (score >= 90 && score <= 100) {
  System.out.println("優秀");
} else if (score >= 80 && score <= 89) {
  System.out.println("良好");
} else if (score >= 60 && score <= 79) {
  System.out.println("及格");
} else if (score >= 0 && score <= 59) {
  System.out.println("不及格");
}
// Kotlin中的if
var score = 100;
if (score >= 90 && score <= 100) {
  System.out.println("優秀");
} else if (score >= 80 && score <= 89) {
  System.out.println("良好");
} else if (score >= 60 && score <= 79) {
  System.out.println("及格");
} else if (score >= 0 && score <= 59) {
  System.out.println("不及格");
}

 

但是如果有自己的特性

// 假設求兩個數的最大值
// java代碼
int a = 3;
int b = 4;
int max = 0;
if(a > b) {
    max = a;
} else {
    max = b;
}

但是在kotlin中, 可以進行優化

var a = 3
var b = 4
var max = 0
max = if(a > b) {
    a
} else {
    b
}
// 只不過寫習慣java后,這樣的形式看起來不習慣

 

另外, kotlin中可以通過in 來表示某個變量的范圍, 能夠代替java中繁瑣的 &&來表示 一個變量的范圍

var score = 100
//  score in 0..59 表示的就是 0 <= score <= 59
// in 表示范圍時, 肯定會包含兩個端點的值, 也就是包含0 和 59 
// 如果想要用in來表示不包含0和59, 如: 0 < score < 59
// 那么就要調整范圍到 1~58, 也就是  score in 1..58
// 使用in后, 代碼可以表示如下形式
if (score in 0..59) {
  print("不及格")
} else if (score in 60..79) {
  print("及格")
} else if (score in 80..89) {
  print("良好")
} else if (score in 90..100) {
  print("優秀")
}

 

when表達式

when表達式和java中的switch類似, 但是java中的switch無法表示一個范圍, 而when可以和in來結合使用, 表示一個范圍

// 基本格式
// 並且不同於java中的switch只能表示 byte short int char String 枚舉等類型, 
// kotlin中的when可以表示很多類型, 比如boolean
var number = true
when (score) {
  true -> {     
    print("hello")
  }
  false -> print("world") // ->后面的大括號, 如果不寫, 那么默認執行最近的一行代碼
  
}

 

// 上面那個if寫的根據不同分數, 做不同輸出的代碼, 如果使用when來做
var score = 100
when(score) {
  in 0..59 -> print("不及格")
  in 60..79 -> print("及格")
  in 80..89 -> print("良好")
  in 90..100 -> print("優秀")
  else -> print("信息有誤")     // 效果和if中的else, switch中的default一樣
}

同樣, 判斷兩個數最大值可以用when表示為:

val a = 3
val b = 4
val max = when(a > b) {     // 這里能夠看到, switch中是不支持a > b這種寫法的, 而when中可以 
  true -> a
  false -> b
}
print(max)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM