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)

 

转载于:https://www.cnblogs.com/sweep/p/8677160.html