Can we represent “self class” in Java (or Kotlin)? [duplicate]

那年仲夏 提交于 2019-12-12 23:05:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!