【发布时间】:2021-02-12 14:23:25
【问题描述】:
我在 Kotlin 中使用类委托,想知道是否可以在 Kotlin 中将委托方法设为私有
interface A{
fun test(name: String)
}
class A1:A{
fun test(name: String): String = name
}
interface C{
fun myTest(name: String)
}
class C1(a:A){
fun myTest(name: String) = a.test(name)
}
class B(a:A): C by C1(a) {
// I can call "mytest" here
fun anotherMethod() = myTest("hi")
//But I want to make "myTest" private
}
val b = B(A1())
//This should not be possible
//b.myTest()
【问题讨论】:
-
您能否修复上面的代码,以便我们更清楚地了解您的尝试?此行没有语义意义,不会编译:
class B(a:A): c by C(a) {There is no interface C. -
对不起!我已经修复了代码。
-
Kotlin 只支持接口的委托,这些接口只有公共成员。为了让它适用于受保护的成员,必须有某种“受保护的接口”,我怀疑他们是否会支持它,因为它的用途有限且缺乏对 JVM 的支持。
标签: kotlin delegation