1

I plan to set my coordinator if only it is type T sent.

interface ViewSurface<T : Coordinator> {
    var coordinator: T

    fun setCoor(coordinator: Coordinator) {
        if (coordinator is T) {
            this.coordinator = coordinator
        }
    }
}

The above code complaint Cannot check for erased type: T. How could I change to get the right syntax yet achieve what I wanted?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Elye
  • 53,639
  • 54
  • 212
  • 474
  • 1
    Probably the same way as with 'standard Java', which is round-about due to .. Type Erasure. See https://stackoverflow.com/q/339699/2864740 for how/why this occurs. But why not only accept `coordinator: T`? – user2864740 Jul 02 '18 at 05:08

1 Answers1

4

Because at runtime, the generic type parameters are all gone (erased), the runtime can't really check whether coordinator is T because it has no idea what T is.

Instead of checking the type of coordinator before assigning it, why not change the parameter type from Coordinator to T so that the compiler can guarantee that coordinator will always be assignable to the coordinator property in the interface?

fun setCoor(coordinator: T) {
    this.coordinator = coordinator
}

As you can see, the setCoor method isn't really needed. You can just set the property normally:

coordinator = ...
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • While this [probably] works in this case, and such a type-sound approach with generics is an improvement overall, it doesn't answer the fundamental question :} At some times one *really does* want to have access to 'the type of T' (even if such itself feeds into an "unsafe" cast). Reified generics makes this trivial, and Java/Kotlin (without such) need to adopt slightly different approaches.. – user2864740 Jul 03 '18 at 17:39
  • @user2864740 I think there are many answers out there that already address this in Java. Like [this](https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t) and [this](https://stackoverflow.com/questions/5734720/test-if-object-is-instanceof-a-parameter-type). If you think a kotlin version is needed. You can post question and answer it yourself. :) – Sweeper Jul 03 '18 at 17:45
  • I do think a Kotlin version would be handy. And that *is* what the OP asked for, even if an XY question. Y might be correct, but X was still asked. – user2864740 Jul 03 '18 at 17:58