首页 > 解决方案 > 私有委托方法

问题描述

我在 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()

标签: kotlindelegation

解决方案


接口用于公开API的功能,如果B是A,那么它必须有一个公共成员测试。

如果您不希望 test() 作为公共成员使用,则不应实施 A:

class B(val a: A) {
    fun anotherMethod() = a.test("hi")
}

推荐阅读