Mor*_*zov 32 string nullable kotlin
以下Kotlin代码:
val x = null + null
Run Code Online (Sandbox Code Playgroud)
结果x是类型String,这是正确的,根据文档String.plus:
将此字符串与给定[other]对象的字符串表示形式连接起来.如果receiver或[other]对象为null,则表示为字符串"null".
但是,我不明白为什么会发生这种情况 - 是否是由于该语言的一些特殊功能?
Bak*_*aii 45
可能是因为String?.plus(Any?)它是唯一plus一个在Kotlin库中接受可空类型作为接收器的函数.因此,当您调用时null + null,编译器会将第一个null视为String?.
如果您定义了接收器类型所在的扩展函数Int?且返回类型为Int,x则将推断为Int.
public operator fun Int?.plus(other: Any?): Int = 1
val x = null + null
Run Code Online (Sandbox Code Playgroud)
如果在同一个文件中声明另一个类似的函数(可接受类型的可空类型),则在调用null + null时会导致编译时错误:Overload resolution ambiguity. All these functions match..
public operator fun Int?.plus(other: Any?): Int = 1
public operator fun Float?.plus(other: Any?): Float = 1F
val x = null + null //compile time error
Run Code Online (Sandbox Code Playgroud)
我们需要从Nothing. 这种类型的可能值正好为零。它是一个底部类型,并且是所有其他类型的子类型(不要与 混淆Any,它是所有其他类型的超类型)。Nothing可以强制为任何类型,以便您可以执行以下操作:
fun doStuff(a: Int): String =
TODO("this typechecks")
Run Code Online (Sandbox Code Playgroud)
继续讨论 的类型Nothing?,意思是Nothing或null。它有 0 + 1 个可能的值。所以null有一种Nothing?. Nothing?可以强制为任何可空类型,以便您可以执行以下操作:
var name: String? = null
Run Code Online (Sandbox Code Playgroud)
这里null : Nothing?被强制到String?.
不幸的是,由于某种原因,在 stdlib 中定义了这个函数:
operator fun String?.plus(other: Any?): String
Run Code Online (Sandbox Code Playgroud)
这允许null + null利用我上面提到的那些强制规则
| 归档时间: |
|
| 查看次数: |
1952 次 |
| 最近记录: |