4

Can we ensure that A<T> is always an instance of T?

open class A<T : A<T>> {
  fun self(): T = this as T // is this safe?
}

or are there any cases where it's not true?

Min Chan
  • 51
  • 1
  • 2
  • How do instantiate one of these (not saying you can't, I just can't work it out :-)) – matt freake Jun 23 '20 at 12:59
  • 1
    @mattfreake You can have `class B : A()` (one example in the stdlib is the `Enum` class) – Min Chan Jun 23 '20 at 13:07
  • 3
    `val a = A()` `val b = a.self() // ClassCastException: class A cannot be cast to class B` – IR42 Jun 23 '20 at 13:09
  • @IR42 oic... even making `open class A> protected constructor()` then `class C : A()` still breaks it – Min Chan Jun 23 '20 at 14:06
  • 1
    See the second part of [this answer](https://stackoverflow.com/a/2165638/7366707) for another example where this doesn't do what you want. As far as I know, it's not possible to _ensure_ that the type parameter is the same as the self type, but this is as close as you can get. – Salem Jun 23 '20 at 14:14
  • I don't believe this is possible because the reference of T is an A, so it cannot be the same thing, it is checking whether the parent (A) is the type of the child (B) which will never resolve. You would have to invert logic, which would ruin the purpose fo the recursion. I would be curious what the application of this logic would be to try and find another solution – Benjamin Charais Jun 23 '20 at 18:40

0 Answers0