【问题标题】:Why doesn't toString throw an exception when called on null value in Kotlin? [duplicate]为什么在 Kotlin 中调用空值时 toString 不抛出异常? [复制]
【发布时间】:2023-03-15 19:23:01
【问题描述】:

给定代码

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

运行时,输出为

null

出现两个问题:

  • 是否可以实现自定义 null 安全方法并回退到某些默认代码(我认为,toString 可以)
  • 为什么不抛出异常?

【问题讨论】:

  • 好的,但是第二个问题呢?这可能吗?

标签: kotlin kotlin-null-safety


【解决方案1】:

来自docs

fun Any?.toString(): String

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

您可以通过编写extension function 来实现类似的行为。例如:

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"
}

Live example.

【讨论】:

  • 有趣的扩展...在任何可为空的对象上调用 foo() 应该可以工作,而不必先断言 not null 或 ?.foo()?
  • @RobinJonsson - 确实。我已经编辑了我的答案以包含一个更完整的示例。
猜你喜欢
  • 2014-09-18
  • 2016-05-10
  • 2021-07-08
  • 2011-10-13
  • 2020-09-30
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
相关资源
最近更新 更多