kotlin,可以调用null.also {}

lan*_*nyf 4 generics nullable kotlin

有代码如:

result.also{......}
Run Code Online (Sandbox Code Playgroud)

但是result可能是null并且编译器没有抱怨,它是相同的

null.also{...}
Run Code Online (Sandbox Code Playgroud)

是否确定打电话also{}null

s1m*_*nw1 10

是的.正如函数定义告诉您:

inline fun <T> T.also(block: (T) -> Unit): T (source)
Run Code Online (Sandbox Code Playgroud)

T没有定义任何上限,因此可以与任何可空和非可空类型一起使用(与之<T>相同<T: Any?>).

如果你害怕NullPointerExceptions,你不需要.在你的情况下,该also函数只是调用block它的接收器,null然后再次返回接收器.例如,以下内容完全正常:

return null.also { println(it) } //returns null and _also_ prints "null"
Run Code Online (Sandbox Code Playgroud)