Necessary typecast for generic sealed class


#1

I have code like this. Task represent some set of operations and generic parameter represents return type of that operation.

data class Person(val name: String)

sealed class Task<T> {
  object LoadPerson: Task<Person>()
}

``` fun perform<T>(task: Task<T>): T = when(task) {   is Task.LoadPerson -> Person("john") } ```

Compiler marks type mismatch in perform function. Required: T found: Person. Maybe I'm just missing something but T cannot be anything else then Person. It works when I explicitly cast it to T.

Is it a limitation of Kotlin? Will it be possible in the future to write such code without typecast?


#2

Hi!

One unrelated question: Why does the “sealed” annotation work for you? I tried “sealed” with the Kotlin plugin for IDEA version 0.12.613 and 0.12.1218 but it didn’t recognize the annotation.


#3

"sealed" is not released yet, so only available in 0.1-SNAPSHOT builds and other artifacts from our "master" branch.


#4

The compiler is simply not smart enough to infer this. I'm not sure whether we are going to add the necessary logic in the near future, because it's rather complicated, and the gain is relatively small