Kotlin:无法从特征访问超类
Kotlin: Superclass is not accessible from trait
在 Kotlin 中,给定一些 class:
public open class A {
open fun sayHi() = "hi"
}
还有一个特征 T 需要 subclasses 来扩展 A :
public trait T : A {
override fun sayHi() = super.sayHi() + " John"
}
人们会期望 T.sayHi
能够调用 super.sayHi()
或更明确的 super<A>.sayHi()
,因为所有类型信息都在那里,但它会产生 Superclass is not accessible from trait
.
问题:
[如何]我可以从 trait 中覆盖某些方法?
备注:
当然,如果不覆盖,我可以这样做:
public trait T : A {
fun another() = sayHi() + " John"
}
但我确实希望我的特质能够 "intercept / be in the middle"。
我不得不使用一些委托来实现类似的行为,但我想知道是否可以使用特征来做到这一点。
正如@Salomon 在他的评论中指出的那样,此功能将在较新版本的 Kotin 中删除,使此问题不再有效。
Required Classes
Some of you might have heard of this feature: traits in Kotlin can
“extend” classes (we actually use the term “require”).
Technically it means that when a class extends such a trait, it must
(directly or indirectly) extend the required class as well. This
feature has very few use cases, so we are deprecating it.
来源:http://blog.jetbrains.com/kotlin/2015/04/upcoming-changes-and-more/
在 Kotlin 中,给定一些 class:
public open class A {
open fun sayHi() = "hi"
}
还有一个特征 T 需要 subclasses 来扩展 A :
public trait T : A {
override fun sayHi() = super.sayHi() + " John"
}
人们会期望 T.sayHi
能够调用 super.sayHi()
或更明确的 super<A>.sayHi()
,因为所有类型信息都在那里,但它会产生 Superclass is not accessible from trait
.
问题:
[如何]我可以从 trait 中覆盖某些方法?
备注:
当然,如果不覆盖,我可以这样做:
public trait T : A {
fun another() = sayHi() + " John"
}
但我确实希望我的特质能够 "intercept / be in the middle"。
我不得不使用一些委托来实现类似的行为,但我想知道是否可以使用特征来做到这一点。
正如@Salomon 在他的评论中指出的那样,此功能将在较新版本的 Kotin 中删除,使此问题不再有效。
Required Classes
Some of you might have heard of this feature: traits in Kotlin can “extend” classes (we actually use the term “require”).
Technically it means that when a class extends such a trait, it must (directly or indirectly) extend the required class as well. This feature has very few use cases, so we are deprecating it.
来源:http://blog.jetbrains.com/kotlin/2015/04/upcoming-changes-and-more/