为什么在Kotlin中调用null值时toString不会引发异常? [英] Why doesn't toString throw an exception when called on null value in Kotlin?

查看:205
本文介绍了为什么在Kotlin中调用null值时toString不会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出代码

fun main(args: Array<String>) {
    val someText: String? = null
    println(someText.toString())
}

运行时,输出为

null

出现两个问题:

  • 是否可以实现自定义的null安全方法,并回退到一些默认代码(例如,我认为toString可以做到)
  • 为什么不引发异常?

推荐答案

来自文档:

fun Any?.toString(): String

返回对象的字符串表示形式.可以用空接收器调用,在这种情况下,它将返回字符串"null".

Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null".

通过编写扩展功能,您可以实现类似的行为.例如:

You can achieve similar behaviour by writing an extension function. For example:

fun Any?.foo() = println(this ?: "Sadly, this is null")

fun main(args: Array<String>) {
    val x: Int? = null
    val y: Int? = 3

    x.foo()       // "Sadly, this is null"
    y.foo()       // "3"
    null.foo()    // "Sadly, this is null"
}

实时示例.

这篇关于为什么在Kotlin中调用null值时toString不会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆