【发布时间】:2019-05-07 00:16:14
【问题描述】:
我是一名 kotlin 学习者 day1。我从https://kotlinlang.org/docs/reference/basic-syntax.html 得到这段代码,然后修改为测试空安全性(https://kotlinlang.org/docs/reference/null-safety.html)
我每行都有错误。 这个 kotlin 空安全性在何时以及如何修复它有什么问题?
fun describe(obj?: Any): String =
when(obj?) {
1 -> "one"
"hello" -> "greeting"
is Long -> "long"
!is String -> "not String"
is null -> "null"
else -> "unknown"
}
fun main() {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe(null))
println(describe("other"))
}
【问题讨论】:
-
你应该在变量类型后面加上问号以表示它可以为空:
fun describe(obj: Any?): ....并在when中删除?。 -
只是一些基本的语法错误。您看到的错误是否为您提供了一些可能出错的提示?
标签: kotlin