Kotlin smartcasting近似于使用时的空值

我想分享一些我在Kotlin 表达时所发现的知识:尽管Kotlin的文档虽然写得简单而且即将出版,但是我可以想象它的写作,但却要求提供一个非常全面的理解。

有两件事现在还不清楚:

  1. when语句如何匹配多个可为空的实例?
  2. 基于函数调用如何匹配?

没有细节,我只会给你代码和结果。 代码中评论了这些发现。 当然,有一些(事后看来)是我首先想到的,但是也有一些令人大开眼界的东西。

 /** * If smaller returns value, then the when statement sees it as a matching case */ fun smaller(value: Int, lt: Int) = if (value < lt) value else lt fun whenTest(value: Int = 5) = when(value) { smaller(value, 1) -> "Smaller than 1" in 1..4 -> "Smaller than Five" 5 -> "Five" else -> "Larger than 5" } /* IMPORTANT NOTES ABOUT INSTANCE TESTS: 1. Evaluation is sequential from top to bottom 2. Smartcasting will, for a box or unboxed type enter the first boxed or unboxed type, whichever is first (see case x...). This is for if an Int? contains an int it enters Int ->, and when it contains a null then it enters null -> 3. Smartcasting on a null value will enter the first null or nullable type case!!! If you switch case c: and x: around then case x: may execute while case c: will never ever execute */ fun patternTest(value: Any?) = when (value) { 10 -> "e: the value is ten" is String -> "a: a string of $value" is Int -> "b: an int of $value" null -> "c: the value is null" is Int? -> "x: never ever executed: an int of $value" else -> "d: ${value.javaClass.name} class with value of $value" } fun main(args: Array<String>) { println("Performing whenTest") println("whenTest(-1) = ${whenTest(-1)}") println("whenTest(2) = ${whenTest(2)}") println("whenTest(5) = ${whenTest(5)}") println("whenTest(7) = ${whenTest(7)}") val nullableInt : Int? = 200 val nonNullableInt : Int = 200 val nulledInt: Int? = null println("patternTest(-1) = ${patternTest(-1)}") println("patternTest($nullableInt) = ${patternTest(nullableInt)}") println("patternTest($nonNullableInt) = ${patternTest(nonNullableInt)}") println("patternTest($nulledInt) = ${patternTest(nulledInt)}") println("patternTest(null) = ${patternTest(null)}") println("patternTest(123.45f) = ${patternTest(123.45f)}") println("patternTest(10) = ${patternTest(10)}") } 

这里是输出:

 Performing whenTest whenTest(-1) = Smaller than 1 whenTest(2) = Smaller than Five whenTest(5) = Five whenTest(7) = Larger than 5 patternTest(-1) = b: an int of -1 patternTest(200) = b: an int of 200 patternTest(200) = b: an int of 200 patternTest(null) = c: the value is null patternTest(null) = c: the value is null patternTest(123.45f) = d: java.lang.Float class with value of 123.45 patternTest(10) = e: the value is ten 
Interesting Posts