kotlin - 为什么 println() 在一种情况下会抛出错误,而在另一种情况下却不会?

标签 kotlin

为什么会这样

println(Int.MIN_VALUE + " " + Int.MAX_VALUE)

抛出错误,而

println("" + Int.MIN_VALUE + " " + Int.MAX_VALUE)

不是吗?

最佳答案

如评论中所述,您的两个语句调用了不同的 plus 函数。 plus 函数是 binary operator function ,这意味着可以使用 infix notation 调用它a + b。这将调用 a 上的运算符函数,并将 b 作为参数。在您的示例中,这意味着

"" + Int.MIN_VALUE

调用 plus defined by String它有 String.plus(other: Any?) 作为它的方法签名。如文档所述,它

Returns a string obtained by concatenating this string with the string representation of the given other object.

这意味着它将通过调用 toString() 方法获得 Int.MIN_VALUEString 表示。

另一方面,

Int.MIN_VALUE + ""

调用 plus defined by Int这限制了它的参数类型并且不能应用于 String,因此 Kotlin 会抛出错误。


附带说明一下,您可能应该使用 string templates无论如何:

"${Int.MIN_VALUE} ${Int.MAX_VALUE}"

关于kotlin - 为什么 println() 在一种情况下会抛出错误,而在另一种情况下却不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70503931/

相关文章:

android - 如何将 Fuel 与 Kotlin 协程一起使用

kotlin - RxKotlin “withLatestFrom(…)”编译错误:没有足够的信息来推断类型变量R

java - 下载带有 MVP 图案的照片

java - Kotlin 中的 Enum.valueOf

kotlin - 我怎样才能做一个有很多变量的 for

android - FusedLocationProviderClient 与 Kotlin 协程

java - Springboot : How to execute custom mongodb query by springboot?

android - 使用 Fragments 实现 Compose 底部导航

syntax - 在 Kotlin 中增加可空 Int 的简单而好方法

kotlin - 如何在 Gradle 构建中使用来自 Kotlin 的孵化 Vector API?