Search code examples
kotlinnullablekotlin-null-safety

Kotlin type mismatch: required Array<Int?>? but found Array<Int>


Here's my Foo data class definition

data class Foo(
    var fooArg: Array<Int?>? = null, 
)

And here's the call to it:

val bar: Array<Int> = arrayOf(1,2,3)
val foo = Foo(fooArg = bar)

But this gives an error type mismatch: required Array<Int?>? but found Array<Int>

I am confused, it is expecting a nullable type, and I provide it with a non-null value, how is that type mismatch?


Solution

  • You declared bar as Array<Int>. Non-null types are not compatible with nullable types*. Change it to Array<Int?> and it will work:

    val bar: Array<Int?> = arrayOf(1,2,3)
    val foo = Foo(fooArg = bar)
    

    Or alternatively:

    val bar = arrayOf<Int?>(1, 2, 3)
    

    *I think the correct thing to say is that arrays are invariant on the type parameter. But I get lost every time I try to understand it properly. 🤯