Error in Line 5 and 6.
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()
}
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
A very different scenario got me to this me to this question, I will share my scenario as it might help others, For me the error was
Type mismatch: inferred type is String? but String was expected
In my case I had declared a var of type String where in fact the method return type was a nullable string ie
var variable:String
had to be var variable:String?
.
Your syntax is incorrect. Try this (using a data class to simplify it and fixing syntax on type declarations - use :
for type declaration, not =
):
data class Robot(val name: String, val color: String) {
fun makeBed() {
println("I will make your bed.")
}
}
fun main(args: Array<String>) {
val robot1 = Robot("Robot1", "Black")
println(robot1.name)
println(robot1.color)
robot1.makeBed()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With