Kotlin第七弹:Kotlin条件控制

左手的ㄟ右手 2024-04-07 15:40 116阅读 0赞

会一直坚持写关于Kotlin的入门系列文章,赶紧关注一起学习吧!

目录

前言

一、if表达式

1、带返回值if表达式

2、if 表达式替代三目运算符

3、多级if表达式

二、When表达式

三、when 表达式的功能增强

1、Kotlin 1.3 版本之前 when

2、Kotlin 1.3 版本之后 when

四、使用 when 表达式替代 if 表达式

总结


#

前言

条件控制是每门编程语言中必不可少的,一般就是使用我们所熟知的 ifelse ,来作为我们代码逻辑选择条件控制。 在 Java 中一般使用 ifelse 和 switch-case 来作为条件控制,而在 Kotlin 中则是使用 if-else 和 when 来作为条件控制。

Tips:Kotlin 中没有 switch-case。


一、if表达式

1、带返回值if表达式

在 Kotlin 中,if 是一个表达式所以它会返回一个值,表达式的值为表达式作 用域内最后一行的值。这一点和 Java 是不同的, 在 Java 中 if 仅仅是语句。

  1. //一般类似 java 中传统 if 的用法
  2. fun maxOf(a: Int, b: Int): Int {
  3. if (a > b) {
  4. return a
  5. } else {
  6. return b
  7. }
  8. }
  9. fun main(args: Array<String>) {
  10. println(maxOf(1, 5))
  11. }
  12. //作为表达式则可以这样
  13. fun maxOf(a: Int, b: Int):Int{
  14. return if (a > b) a else b
  15. }
  16. fun main(args: Array<String>) {
  17. println(maxOf(1, 5))
  18. }

if 表达式分支可以是代码块,也可以把作用域内最后一行表达式的值作为该 分支块的值:

  1. fun maxOf(a: Int, b: Int) = if(a > b) {
  2. println(a)
  3. a //返回值为 a
  4. } else {
  5. println(b)
  6. b //返回值为 b
  7. }
  8. fun main(args: Array<String>) {
  9. println(maxOf(1, 5))
  10. }

2、if 表达式替代三目运算符

因为在 Kotlin 中 if 表达式是带有返回值的,所以在 Kotlin 中是不需要三目 运算符(xxx ? xxx : xxx), 因为 if 表达式这些都能做到。

  1. //Java 中三目运算符
  2. public int maxOf(int a, int b) {
  3. return a > b ? a : b;
  4. }

而在 Kotlin 中则可以直接使用 if 表达式来使用:

  1. //Kotlin 中的 if 表达式
  2. fun maxOf(a: Int, b: Int) = if (a > b) a else b

Tips:如果你使用 if 作为表达式而不是语句(例如:返回它的值或者把它赋 给变量),该表达式需要有 else 分支 。

3、多级if表达式

和 Java 一样 Kotlin 也支持 if-else if-else 等多级条件选择,但是一般如 果这种带多级条件选择的 IDE 会提示你使用 when 表达式来替代: 下面这个案例会使用 if-else if-else 来判断变量 number 是何种数据类型:

  1. fun eval(number: Number) {
  2. if (number is Int) {
  3. println("this is int number")
  4. } else if (number is Double) {
  5. prinln("this is double number")
  6. } else if (number is Float) {
  7. println("this is float number")
  8. } else if (number is Long) {
  9. println("this is long number")
  10. } else if (number is Byte) {
  11. println("this is byte number")
  12. } else if (number is Short) {
  13. println("this is Short number")
  14. } else {
  15. throw IllegalArgumentException("invalid argument")
  16. }
  17. }

但是需要注意的是 如果 eval 函数需要有返回值的时候,必须要有 else 分支。


二、When表达式

在 Kotlin 中使用 when 表达式替代了类似 C 语言的 switch-case 语句。其中 最简单的形式如下:

  1. fun eval(number: Number): String = when (number) {
  2. is Int -> "this is int number"
  3. is Double -> "this is double number"
  4. is Float -> "ths is float number"
  5. is Long -> "this is long number"
  6. is Byte -> "this is byte number"
  7. is Short -> "this is Short number"
  8. else -> "invalid number"
  9. }
  10. //多种条件判断混合形式
  11. fun main(args: Array<String>) {
  12. println(descript("hello"))
  13. }
  14. fun descript(obj: Any): String = when (obj) {
  15. 1 -> "one"
  16. "hello" -> "hello word"
  17. is Long -> "long type"
  18. !is String -> "is not String"
  19. else -> {
  20. "unknown type"
  21. }
  22. }

when 将它的参数与所有的分支条件顺序比较,直到某个分支满足条 件。 when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做 表达式, 符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。(像 if 一样,每一个分支可以是一个代码块,它的值 是块中最后的表达式的值。)

Tips:如果其他分支都不满足条件将会求值 else 分支。 如果 when 作为一 个表达式使用,则必须有 else 分支, 除非编译器能够检测出所有的可能情 况都已经覆盖了。

如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用 逗号分隔:

  1. fun eval(any: Any): String = when (any) {
  2. is Int, Double, Float, Long, Byte, Short -> "this is number" //多个分
  3. 支条件放在一起,用逗号分隔
  4. is Char -> "this is char"
  5. else -> "other"
  6. }

when 也可以用来取代 if-else if 链。 如果不提供参数,所有的分支条件都是 简单的布尔表达式,而当一个分支的条件为真时则执行该分支:

  1. fun eval(number: Number) {
  2. when {
  3. number.isOdd() -> {
  4. println("this is odd number")
  5. }
  6. number.isEven() -> {
  7. println("this is even number")
  8. }
  9. else -> println("this is invalid number")
  10. }
  11. }

三、when 表达式的功能增强

自从 Kotlin1.3 版本后对 when 表达式做了一个写法上的优化,为什么这么 说呢? 仅仅就是写法上的优化,实际上什么都没做. 它主要是解决什么问题 呢?细心的小伙伴会发现,在 Kotlin 1.3 版本之前 when 表达式内部是不能使 用传入的值的。

1、Kotlin 1.3 版本之前 when

  1. fun main(args: Array<String>) {
  2. val value = getValue() //可以看到 1.3 版本之前需要多出来一步
  3. when (value) {
  4. is Int -> "This is Int Type, value is $value".apply(::println) //
  5. 注意这里 when 中获得 value 不是 when 直接传入 value,而是 when 外部声明 value
  6. is String -> "This is String Type, value is
  7. $value".apply(::println)
  8. is Double -> "This is Double Type, value is
  9. $value".apply(::println)
  10. is Float -> "This is Float Type, value is $value".apply(::println)
  11. else -> "unknown type".apply(::println)
  12. }
  13. }
  14. fun getValue(): Any {
  15. return 100F
  16. }

我们可以尝试把 kotlin 1.3 版本之前 when 表达式使用代码反编译成 Java 代码:

  1. public static final void main(@NotNull String[] args) {
  2. Intrinsics.checkParameterIsNotNull(args, "args");
  3. Object value = getValue();
  4. String var3;
  5. if (value instanceof Integer) {
  6. var3 = "This is Int Type, value is " + value;
  7. System.out.println(var3);
  8. } else if (value instanceof String) {
  9. var3 = "This is String Type, value is " + value;
  10. System.out.println(var3);
  11. } else if (value instanceof Double) {
  12. var3 = "This is Double Type, value is " + value;
  13. System.out.println(var3);
  14. } else if (value instanceof Float) {
  15. var3 = "This is Float Type, value is " + value;
  16. System.out.println(var3);
  17. } else {
  18. var3 = "unknown type";
  19. System.out.println(var3);
  20. }
  21. }
  22. @NotNull
  23. public static final Object getValue() {
  24. return 100.0F;
  25. }

2、Kotlin 1.3 版本之后 when

  1. fun main(args: Array<String>) {
  2. when (val value = getValue()) {//when 表达式条件直接是一个表达式,并用
  3. value 保存了返回值, 实际上相当于把外部那一行缩进来写
  4. is Int -> "This is Int Type, value is $value".apply(::println)
  5. is String -> "This is String Type, value is
  6. $value".apply(::println)
  7. is Double -> "This is Double Type, value is
  8. $value".apply(::println)
  9. is Float -> "This is Float Type, value is $value".apply(::println)
  10. else -> "unknown type".apply(::println)
  11. }
  12. }
  13. fun getValue(): Any {
  14. return 100F
  15. }

通过对比发现,Kotlin 1.3 前后 when 表达式的增强,仅仅是把原来外部那一行代码,缩 进到 when 里写,然而两次写法反编译的 Java 代码是一致的。

四、使用 when 表达式替代 if 表达式

和 if 表达式一样,when 表达式也是带有返回值的。建议对于多层条件级或嵌 套条件控制的使用建议使用 when 替代 if-else:

  1. fun eval(number: Number) {
  2. if (number is Int) {
  3. println("this is int number")
  4. } else if (number is Double) {
  5. println("this is double number")
  6. } else if (number is Float) {
  7. println("this is float number")
  8. } else if (number is Long) {
  9. println("this is long number")
  10. } else if (number is Byte) {
  11. println("this is byte number")
  12. } else if (number is Short) {
  13. println("this is Short number")
  14. } else {
  15. throw IllegalArgumentException("invalid argument")
  16. }
  17. }
  18. //多层级条件使用 when 表达式
  19. fun eval(number: Number): String = when (number) {
  20. is Int -> "this is int number"
  21. is Double -> "this is double number"
  22. is Float -> "ths is float number"
  23. is Long -> "this is long number"
  24. is Byte -> "this is byte number"
  25. is Short -> "this is Short number"
  26. else -> "invalid number"
  27. }

总结

到这里 Kotlin 中的条件控制就阐述完毕了,可以发现 Kotlin 中条件控制和 Java 还是存在着很多的不一样的,需要多多练习多多理解,下一篇我们将进 入 Kotlin 中循环控制。

#

发表评论

表情:
评论列表 (有 0 条评论,116人围观)

还没有评论,来说两句吧...

相关阅读