Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Type mismatch: inferred type is String but String.Companion was expected

Tags:

kotlin

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()
}
like image 724
user8823037 Avatar asked Apr 28 '18 19:04

user8823037


3 Answers

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
like image 94
s1m0nw1 Avatar answered Sep 19 '22 08:09

s1m0nw1


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

like image 36
Mightian Avatar answered Sep 19 '22 08:09

Mightian


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()
}
like image 21
Renato Avatar answered Sep 23 '22 08:09

Renato