Why does type inference fail for `extract` here? `...
# announcements
s
Why does type inference fail for
extract
here?
Copy code
object Container {
    val contained = mutableMapOf<String, Any>()

    inline fun <reified T> extract(name: String): T = contained[name] as T
}

class Foo {
    val bar: String by lazy {
        Container.extract("Bar")
    }
}
Because
lazy
is declared to return a
String
, shouldn’t the inferred type
T
also be
String
?
f
The current type inference is not that great, you can try
-Xnew-inference
(your example works with it).
👍 1
z
What type is it inferring?
f
None, it fails to inferre anything.
z
What’s the error you’re getting?
And where in that snippet?
s
Why does type inference fail for
extract
here?
z
Sorry, I wasn’t clear. I don’t see anything in the given code that would require any types to be inferred. Is the compiler telling you to write
lazy<String>
? Sorry if this is obvious, maybe I need another coffee…
s
The
reified T
of
extract
should be inferred from the return value of
lazy
but isn’t with the current implementation of type inferrence.
f
Inside
lazy
writing
Container.extract<String>("Bar")
is where it fails.
👍 1
s
@Fleshgrinder Not exactly, to make the type checker happy you need
Container.extract<String>("Bar")
but my point was
Container.extract("Bar)"
should be valid because generic type should match the return value of
lazy
f
I was just answering to @Zach Klippenstein (he/him) [MOD] because he specifically asked where the additional type is required. I know what's going on. 😉
👍 1