我们可以在 Java(或 Kotlin)中表示 "self class" 吗?
Can we represent "self class" in Java (or Kotlin)?
我觉得问题标题有点混乱,但我找不到更准确的说法。
我只需要一个简单的代码示例来告诉你我想要什么。
我有:
// 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; } }
但实际上,这段代码也可以通过编译(区别:查看 return 类型声明):
// 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; } }
我希望代码 2 是类型错误。
说,我想将每个 A
's subclass' bla
方法强制为 return 他们自己,而不是 A
.
我认为可以有一个假代码来表示我想要的:
interface A { this.Type bla(); }
就像Haskell的类型类:
class Monad (m :: * -> *) where
-- here m is restricted to the subclass
(>>=) :: m a -> (a -> m b) -> m b
这可能吗?
不可能,但你可以做到
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; } }
我觉得问题标题有点混乱,但我找不到更准确的说法。
我只需要一个简单的代码示例来告诉你我想要什么。
我有:
// 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; } }
但实际上,这段代码也可以通过编译(区别:查看 return 类型声明):
// 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; } }
我希望代码 2 是类型错误。
说,我想将每个 A
's subclass' bla
方法强制为 return 他们自己,而不是 A
.
我认为可以有一个假代码来表示我想要的:
interface A { this.Type bla(); }
就像Haskell的类型类:
class Monad (m :: * -> *) where
-- here m is restricted to the subclass
(>>=) :: m a -> (a -> m b) -> m b
这可能吗?
不可能,但你可以做到
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; } }