我们可以代表“自类"吗?在Java(或Kotlin)中? [英] Can we represent "self class" in Java (or Kotlin)?
本文介绍了我们可以代表“自类"吗?在Java(或Kotlin)中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为问题标题有点令人困惑,但是我找不到更准确的说法.
我只需要一个简单的代码示例即可告诉您我想要什么.
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.
我有:
// 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; } }
我希望代码2是类型错误.
说,我想强制每个A
的子类的bla
方法返回其自身,而不是A
.
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(); }
就像Haskell的类型类一样:
Just like Haskell's typeclasses:
class Monad (m :: * -> *) where
-- here m is restricted to the subclass
(>>=) :: m a -> (a -> m b) -> m b
这可能吗?
推荐答案
不可能,但是你可以做到
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; } }
这篇关于我们可以代表“自类"吗?在Java(或Kotlin)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文