Kotlin:类型不匹配:推断的类型为String但应为String.Companion [英] Kotlin: Type mismatch: inferred type is String but String.Companion was expected
本文介绍了Kotlin:类型不匹配:推断的类型为String但应为String.Companion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第5行和第6行出现错误.
Error in Line 5 and 6.
科特琳:类型不匹配:推断的类型为String,但String.Companion是预期的
Kotlin: Type mismatch: inferred type is String but String.Companion was expected
class Robot (name: String,color :String) {
var roboName= String
var roboColor= String
init {
this.roboName=name
this.roboColor=color
}
fun makeBed()
{
println("I will make your bed.")
}
}
fun main(args: Array<String>){
var robot1=Robot("Robot1","Black")
println(robot1.roboName)
println(robot1.roboColor)
robot1.makeBed()
}
推荐答案
您分配 String
变量,该变量引用了 String.Companion 代码>对象.这也使属性的类型为
String.Companion
.您要做的是定义属性的类型:
You assigned String
to a variable, which refers to the String.Companion
object. This makes the property's type String.Companion
, too. What you want to do instead, is defining the type of your property:
var roboName: String
此外,您可以更进一步,并在声明中加入赋值:
In addition, you can go a step further and join declaration with assignment:
var roboName: String = name
var roboColor: String = color
这篇关于Kotlin:类型不匹配:推断的类型为String但应为String.Companion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文