为什么会这样
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_VALUE
的 String
表示。
另一方面,
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/