我需要知道为什么? 如果我把这行改为“println(name + two)”错误解决?
fun main(args:Array){ val two=2 val name:String? name="Mensh" println(two+name) }
这是一个简单的kotlin应用程序,我得到了println(two+name)
的错误:
Error:(8, 16) Kotlin: None of the following functions can be called with the arguments supplied: public final operator fun plus(other: Byte): Int defined in kotlin.Int public final operator fun plus(other: Double): Double defined in kotlin.Int public final operator fun plus(other: Float): Float defined in kotlin.Int public final operator fun plus(other: Int): Int defined in kotlin.Int public final operator fun plus(other: Long): Long defined in kotlin.Int public final operator fun plus(other: Short): Int defined in kotlin.Int
这在Kotlin中不能编译的原因是因为在连接时没有将数字隐式转换为字符串,这与Java不同。
例如,这将编译:
fun main(args:Array) { val two = 2 val name = "Mensh" println(two.toString() + name) }
正如其他人所说,字符串模板将是一个更习惯于这样做的方式。
其他答案给你的解决方案,但不是解释你的错误。
Error:(8, 16) Kotlin: None of the following functions can be called with the arguments supplied: public final operator fun plus(other: Byte): Int defined in kotlin.Int public final operator fun plus(other: Double): Double defined in kotlin.Int public final operator fun plus(other: Float): Float defined in kotlin.Int public final operator fun plus(other: Int): Int defined in kotlin.Int public final operator fun plus(other: Long): Long defined in kotlin.Int public final operator fun plus(other: Short): Int defined in kotlin.Int
Kotlin有+
运算符的运算符重载 。
println(two+name)
:这里的编译器试图使用Int
运算符的重载函数,它有一个String
参数,但是没有这个函数。 因此,你会得到上述错误。 你可以在上面的错误中看到所有加上运算符重载的函数。
println(name+two)
:但是String
有一个加运算符重载函数,它接受Any?
参数。 所以你没有得到任何错误。 这是字符串的加运算符重载函数:
public operator fun plus(other: Any?): String
Kotlin有自己的格式化字符串的风格,试试:
println("$two$name")
在Kotlin中,可以使用字符串模板进行连接:
val c = "$two $name" print(c)
其他信息在这里。
- 使用意向操作在Android Studio中创建Kotlin类
- 在Eclipse Maven项目中使用Kotlin Javascript进行DOM操作
- 使用maven在kotlin中编写JSP – 错误实例化Servlet类,ClassNotFoundException
- 如何在这个案例中使用“for”
- kotlin文件不支持用markdown写的流程图吗?
- 如何在现有的Android应用程序中使用Kotlin?
- 未解决的参考
- Android Kotlin创建类实现Parcelable在writeToParcel方法的“覆盖”中给出一个错误
- 在压缩AsyncTask中的位图时引发的exception不会停止执行