Search code examples
stringkotlintype-mismatch

Kotlin - Type mismatch: Required: String, Found: () -> String


In Kotlin I declared a List<String> like this:

private val items = listOf<String> {
        "String1",
        "String2",
        "String3"
    }

the compiler is giving me this error:

Type Mismatch.

Required: String

Found: () -> String

What does it mean? How do I fix it?

P.S. Pretty new to Kotlin so bear with me for asking something obvious.


Solution

  • You passed the argument enclosed in {} which introduced a function literal (lambda) which is why the compiler finds a function type

    Found: () -> String

    Instead just use parentheses like this:

    listOf("String1", "String2")
    

    Some information:

    Kotlin allows you to pass functions after the () when passed as the last argument. The parentheses can be left away if the function is the only argument as in your example. Therefore the code is valid but simply does not match the function parameter type.