/errors/kotlin/type-mismatch-inferred-type-is-but-was-expected
Kotlin: Type mismatch: inferred type is String? but String was expected
- tool
- Kotlin
- exit code
- 1
- versions
- Kotlin 1.x (Type mismatch: inferred type is ...), Kotlin 2.x K2 compiler (argument/initializer/assignment type mismatch)
- os
- any
Type mismatch: inferred type is String? but String was expected means an expression of one type is used where Kotlin requires another, and Kotlin does not convert between them on its own. With String? vs String the value may be null and the target does not accept null: give a default with ?:, check for null first, or change the target type. Between unrelated types (String vs Int), convert explicitly with toInt(), toString() and similar functions.
What it looks like
The same file compiled with the Kotlin 2.3 command-line compiler, first with the K1 front end (-language-version 1.9), then with the default K2 compiler:
fun greet(name: String) = println("Hello, $name")
fun main() {
val name: String? = readLine()
greet(name)
var count: Int = 0
count = "3"
}
fun parse(s: String): Int = swarning: language version 1.9 is deprecated in JVM and its support will be removed in a future version of Kotlin
Main.kt:5:11: error: type mismatch: inferred type is String? but String was expected
greet(name)
^^^^
Main.kt:7:13: error: type mismatch: inferred type is String but Int was expected
count = "3"
^^^
Main.kt:10:29: error: type mismatch: inferred type is String but Int was expected
fun parse(s: String): Int = s
^K2 (Kotlin 2.0 and later) names the place where the mismatch happens:
Main.kt:5:11: error: argument type mismatch: actual type is 'String?', but 'String' was expected.
Main.kt:7:13: error: assignment type mismatch: actual type is 'String', but 'Int' was expected.
Main.kt:10:29: error: return type mismatch: expected 'Int', actual 'String'.A declaration such as val n: String = name reports initializer type mismatch: expected 'String', actual 'String?'. in K2.
Fixes for nullable values
val name: String? = readLine()
greet(name ?: "guest") // default when null
if (name != null) greet(name) // smart cast to String inside the if
name?.let { greet(it) } // run only when not null
greet(requireNotNull(name) { "name is required" }) // fail with a clear messageFixes for different types
| Mismatch | Conversion |
|---|---|
| String to Int | "3".toInt(), or "3".toIntOrNull() for user input |
| Int to String | count.toString() or a string template "$count" |
| Int to Long or Double | n.toLong(), n.toDouble() (no implicit widening) |
| Any to a specific type | value as? User (safe cast, null if it is not a User) |