I do not understand why casting `this` to `S` is ...
# announcements
g
I do not understand why casting
this
to
S
is unchecked. Is it a bug or I miss something
n
probably because the compiler cannot infer it regarding how the class uses generics i can understand why infinite recursion is not compiler-friendly
n
looks like what is known in C++ as "CRTP" 🙂
v
Why should
AbstractBuilder
be of type
S
?
n
Other way round -
S
should derive from
AbstractBuilder<S>
, so an instance of
AbstractBuilder<S>
can be downcast to
S
. However, someone could do:
Copy code
class A : AbstractBuilder<B> {}
class B : AbstractBuilder<A> {}
and then the cast fails, but the JVM can't check it as it's unchecked
v
Ah, ugh, that looks like a pretty confusing and error-prone pattern to me.
1
n
In C++ it's quite common but you have to be careful, yes. Not sure about Kotlin
g
AFAIK this pattern is used in Java streams
v
Really? I'm curious, do you know where?
g
Copy code
public interface BaseStream<T, S extends BaseStream<T, S>>
n
yes, this pattern is used no, it’s not a good idea 😉
v
Ah, right
n
all in all, the compiler tells you he cannot be sure about the cast but if you’re sure, that’s ok nothing is wrong
👍 1
m
d
Actually this pattern (with recursive generic) may be replaced with new language feature with self types But it's unknown, would it be added to language or not (but we considering it)
🆒 1