【问题标题】:Can we represent "self class" in Java (or Kotlin)? [duplicate]我们可以在 Java(或 Kotlin)中表示“自我类”吗? [复制]
【发布时间】:2017-12-18 03:07:25
【问题描述】:

我认为问题的标题有点混乱,但我找不到更准确的说法。
我只需要一个简单的代码示例来告诉你我想要什么。

我有:

// 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; } }

但实际上,这段代码也会编译(差异:查看返回类型声明):

// 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 的子类'bla 方法返回他们自己,而不是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

这可能吗?

【问题讨论】:

  • 在 Java 中不可能,不了解 Kotlin。
  • 哦不,坏消息 TAT @Oleg
  • @ice1000 我用过这个库,我想这就是你要找的:github.com/h0tk3y/kotlin-monads ;)
  • @NeilLocketz 我打开了你的链接,在右上角看到Unstar...哈哈
  • 太搞笑了!哈哈哈

标签: java kotlin subtyping


【解决方案1】:

不可能,但你可以这样做

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; } }

【讨论】:

  • 啊,非常感谢! prpr
猜你喜欢
  • 2016-09-11
  • 2011-08-20
  • 2017-12-23
  • 2020-11-07
  • 2023-03-28
  • 1970-01-01
  • 2017-10-04
  • 2014-04-19
  • 1970-01-01
相关资源
最近更新 更多