Tips: There is no switch-case in Kotlin.
1. If expression
1. If expression with return value
In Kotlin, if is an expression so it returns a value, and the value of the expression is the value of the last row in the scope of the expression. This is different from Java. In Java, if is just a statement.
//Generally similar to the traditional usage of if in javafun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } fun main(args: Array<String>) { println(maxOf(1, 5)) } // As an expression, it can be donefun maxOf(a: Int, b: Int):Int{ return if (a > b) a else b } fun main(args: Array<String>) { println(maxOf(1, 5)) }
If expression branches can be code blocks, or the value of the last line of expression in scope can be used as the value of the branch block:
fun maxOf(a: Int, b: Int) = if(a > b) { println(a) a //The return value is a} else { println(b) b //The return value is b} fun main(args: Array<String>) { println(maxOf(1, 5)) }
2. If expression replaces the trigonometric operator
Because the if expression has a return value in Kotlin, the trilogy operator (xxx ? xxx : xxx) is not needed in Kotlin, because if expressions can all do this.
//Triple-object operator in Javapublic int maxOf(int a, int b) { return a > b ? a : b; }
In Kotlin, you can use if expression directly:
// if expression in Kotlinfun maxOf(a: Int, b: Int) = if (a > b) a else b
Tips: If you use if as an expression instead of a statement (for example: return its value or assign it to a variable), the expression needs to have an else branch.
3. Multi-level if expression
Like Java, Kotlin also supports multi-level conditional selection such as if-else, but generally if this IDE with multi-level conditional selection will prompt you to use the when expression instead: In the following case, if-else if-else is used to determine what data type the variable number is:
fun eval(number: Number) { if (number is Int) { println("this is int number") } else if (number is Double) { prinln("this is double number") } else if (number is Float) { println("this is float number") } else if (number is Long) { println("this is long number") } else if (number is Byte) { println("this is byte number") } else if (number is Short) { println("this is Short number") } else { throw IllegalArgumentException("invalid argument") } }
However, it should be noted that if the eval function needs to have a return value, it must have an else branch.
2. When expression
Use the when expression in Kotlin to replace the switch-case statement similar to C language. The simplest form is as follows:
fun eval(number: Number): String = when (number) { is Int -> "this is int number" is Double -> "this is double number" is Float -> "ths is float number" is Long -> "this is long number" is Byte -> "this is byte number" is Short -> "this is Short number" else -> "invalid number" } //Mixed forms of multiple conditionsfun main(args: Array<String>) { println(descript("hello")) } fun descript(obj: Any): String = when (obj) { 1 -> "one" "hello" -> "hello word" is Long -> "long type" !is String -> "is not String" else -> { "unknown type" } }
When Compare its parameters with all branch conditions in sequence until a branch meets the conditions. When can be used as an expression or as a statement. If it is treated as an expression, the value of the branch that meets the conditions is the value of the entire expression. If used as a statement, the value of individual branches is ignored. (Like if, each branch can be a block of code, and its value is the value of the last expression in the block.)
Tips: If no other branches meet the criteria, the else branch will be evaluated. If used as an expression, there must be an else branch unless the compiler can detect that all possible situations have been overwritten.
If many branches need to be processed in the same way, you can put multiple branch conditions together and separate them with commas:
fun eval(any: Any): String = when (any) { is Int, Double, Float, Long, Byte, Short -> "this is number" //Multiple pointsPut together conditions,Separated by commas is Char -> "this is char" else -> "other" }
When can also be used instead of if-else if chain. If no parameters are provided, all branch conditions are simple Boolean expressions, and when the condition of a branch is true, the branch is executed:
fun eval(number: Number) { when { () -> { println("this is odd number") } () -> { println("this is even number") } else -> println("this is invalid number") } }
3. When the function of expression is enhanced
Since Kotlin1.3 version, I have made a writing optimization on when expression. Why do I say that? It is just an optimization on writing, but I actually did nothing. What problem does it mainly solve? Careful friends will find that before Kotlin version 1.3, the value passed in cannot be used inside the expression.
1. Before Kotlin version 1.3
fun main(args: Array<String>) { val value = getValue() //You can see that before version 1.3, you need one more step when (value) { is Int -> "This is Int Type, value is $value".apply(::println) // Pay attention here when Obtained in value no when Directly transferred value,But when External Statement value is String -> "This is String Type, value is $value".apply(::println) is Double -> "This is Double Type, value is $value".apply(::println) is Float -> "This is Float Type, value is $value".apply(::println) else -> "unknown type".apply(::println) } } fun getValue(): Any { return 100F }
We can try to decompile the expression before kotlin version 1.3 into Java code:
public static final void main(@NotNull String[] args) { (args, "args"); Object value = getValue(); String var3; if (value instanceof Integer) { var3 = "This is Int Type, value is " + value; (var3); } else if (value instanceof String) { var3 = "This is String Type, value is " + value; (var3); } else if (value instanceof Double) { var3 = "This is Double Type, value is " + value; (var3); } else if (value instanceof Float) { var3 = "This is Float Type, value is " + value; (var3); } else { var3 = "unknown type"; (var3); } } @NotNull public static final Object getValue() { return 100.0F; }
2. After Kotlin version 1.3
fun main(args: Array<String>) { when (val value = getValue()) {//When expression condition is directly an expression and usesvalue Saved return value, In fact, it is equivalent to indenting the external line and writing is Int -> "This is Int Type, value is $value".apply(::println) is String -> "This is String Type, value is $value".apply(::println) is Double -> "This is Double Type, value is $value".apply(::println) is Float -> "This is Float Type, value is $value".apply(::println) else -> "unknown type".apply(::println) } } fun getValue(): Any { return 100F }
Through comparison, it was found that the enhancement of when expressions before and after Kotlin 1.3 is simply to reduce the original external line of code into when writing, but the Java code decompiled the two writing methods are consistent.
4. Use when expression instead of if expression
Like if expressions, the when expression also has a return value. It is recommended to use when instead of if-else for the use of multi-layer conditional level or nested conditional control:
fun eval(number: Number) { if (number is Int) { println("this is int number") } else if (number is Double) { println("this is double number") } else if (number is Float) { println("this is float number") } else if (number is Long) { println("this is long number") } else if (number is Byte) { println("this is byte number") } else if (number is Short) { println("this is Short number") } else { throw IllegalArgumentException("invalid argument") } } //Multi-level conditions use when expressionfun eval(number: Number): String = when (number) { is Int -> "this is int number" is Double -> "this is double number" is Float -> "ths is float number" is Long -> "this is long number" is Byte -> "this is byte number" is Short -> "this is Short number" else -> "invalid number" }
Summarize
At this point, the conditional control in Kotlin has been explained. It can be found that there are still many differences between conditional control in Kotlin and Java. We need to practice and understand more. In the next article, we will enter the circular control in Kotlin.
This is the article about the summary explanation of Kotlin conditional control statements. For more related Kotlin conditional control content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!