nz_21
nz_21

Reputation: 7343

Type inference fails on parameterized types

Say we have following types:

abstract class Generic_B

interface Generic_A<Generic_B>

class Concrete_B : Generic_B()

class Concrete_A : Generic_A<Concrete_B>

fun main(args: Array<String>) {
    val a = Concrete_A();
    foo(a);
}

fun foo(thing: Generic_A<Generic_B>) {
}

I'm getting an error saying:

Error:(27, 9) Kotlin: Type mismatch: inferred type is Concrete_A but Generic_A<Generic_B> was expected

I don't quite understand the error.

Concrete_A is an instance of Generic_A and also parameterized on a concrete instance of Generic_B. As such, I feel like the type inference should match up.

I guess me questions are:

  1. Why is the type inference not working? (is this a case of higher kinded polymorphism?)
  2. How do I work around this?

Upvotes: 0

Views: 69

Answers (1)

tynn
tynn

Reputation: 39843

Basically you just run into the issue that Generic_A<Generic_B> is not the same as Generic_A<Concrete_B>, which Concrete_A extends.

If you add the out variance to the thing parameter generic part, you'll have it working, as it would accept all subtypes of Generic_B:

fun foo(thing: Generic_A<out Generic_B>) {
}

Upvotes: 4

Related Questions