Kotlin smartcasting近似于使用时的空值

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

有两件事现在还不清楚:

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

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

One Solution collect form web for “Kotlin smartcasting近似于使用时的空值”

 /** * 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 
  • 如何从Gradle迁移到Kobalt?
  • Android Studio 3 Kotlin版本
  • 无法使用JAXB和Kotlin解组xml对象
  • 禁用按钮
  • 如何在同一个src文件夹中运行不同的.kt文件/类?
  • 为什么HashMap.get不能返回一个可为空的类型?
  • 如何对列表中的元素的所有组合执行操作?
  • 在Kotlin中使用@ EnableNeo4jRepositories(basePackageClasses =“myApp”)
  • 你能在Kotlin的运行时连接语句吗?
  • get和在Kotlin中的区别是什么?
  • 什么访问修饰符可测试辅助方法?
  • Kotlin language will be the best programming language for Android.