Type mismatch: inferred type is String? but String was expected

Hi, can I know why is my mistake here? I also have tried to put a “?” after the “String” at line 18 to resolve this problem but it doesn’t work…

The Class header looks like this:
class Congratulations(val name: String)

Hi welcome :slight_smile:

Which lesson is this from? Could you possibly link it when you have a chance?

This lesson is from Classes in Learn Kotlin course

Lesson: Classes

Try var learnerName: readLine().
I think the type declaration is throwing it off.

Tried. Cannot because learnerName variable must follow by a data type(Int, String and bla…) after the colon!

You can then do a toString() method. This should remove that issue. learnerName.toString()

Like, var toLearner = Congratulations(learnerName.toString())

1 Like

Oh, yeah. It works already. Thank you so much for your help!!! :heart:

Btw, can I know why need to add .toString() function to cast the variable to String type as it is already String type

1 Like

Looking at the documentation for readLine() https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/read-line.html

we see that it takes a String?. The ? symbol means that this string is nullable. I’m not too familiar with Kotlin but one thing I do notice is that it seems to be very strict about ambiguity (it’s that one pedantic friend everyone has). Therefore toString() removes the doubt that it will be a null value.

It probably has to do with its compiling process.


I see. Tq so much for your help!

1 Like

It is very picky on 2 things I have noticed var vs var and print() vs println()
I am mainly Python but to create apps in Andriod Studio is a function of Jave and Kotlin.