问题
I think the question title is a little bit confusing, but I can't find a more precise way to say this.
I just need a simple code example to tell you what I want.
I have:
// code 1
interface A { A bla(); }
class B implements A { @Override public B bla() { return this; } }
class C implements A { @Override public C bla() { return this; } }
But actually, this code will compile too (diff: look at the return type declaration):
// code 2
interface A { A bla(); }
class B implements A { @Override public A bla() { return this; } }
class C implements A { @Override public A bla() { return this; } }
I want code 2 to be a type error.
Say, I want to force every A
's subclass' bla
method to return their self, instead of an A
.
I think there can be a fake code to represent what I want:
interface A { this.Type bla(); }
Just like Haskell's typeclasses:
class Monad (m :: * -> *) where
-- here m is restricted to the subclass
(>>=) :: m a -> (a -> m b) -> m b
Is this possible?
回答1:
Not possible, but you can do that
interface A<T extends A> { T bla();}
class B implements A<B> { @Override public B bla() { return this; } }
class C implements A<C> { @Override public C bla() { return this; } }
来源:https://stackoverflow.com/questions/47861636/can-we-represent-self-class-in-java-or-kotlin