5
votes

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()
}
5

5 Answers

9
votes

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
5
votes

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?.

0
votes

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()
}
0
votes

You have to add the variable like this:

var roboName: String
var roboColor: String
0
votes

You Can use lateinit keyword at beginning of the declaration.

class Robot (name: String,color :String) {
    lateinit var roboName = String
    lateinit var roboColor = String
    init {
        this.roboName=name
        this.roboColor=color
    }
    fun makeBed() {
        println("I will make your bed.")
    }
}

fun main(args: Array&lt;String>) {
    var robot1 = Robot("Robot1","Black")
    println(robot1.roboName)
    println(robot1.roboColor)
    robot1.makeBed()
}