【问题标题】:Private Delegated method私有委托方法
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 这很好,但我想通过某种方式将其设为私有。在 Ruby 中,我们有办法将委托方法设为私有。在 ROR 6 中,您只需执行 delegate :first_name, :last_name, to: :@user, private: true 并且 first_name 和 last_name 将是私有的
  • @Arithmeticbird 没有涉及接口if I pointed to correct post,kotlin 有严格的类型系统,ruby 似乎没有(因为没有涉及类型注释)。顺便说一句,您需要做什么?可见性在接口中定义为公共的,继承者必须遵循它。为什么要实现interface A
  • 嗯,是的,我在示例中进行了更改以明确意图。在显式委托(没有 kotlin 语言支持)中,我可以轻松地将方法设为私有。我不明白为什么我们不能通过语言支持来做到这一点。显式委托class B(val a: A) { fun anotherMethod() = a.test("hi") private fun test(name:String) = a.test(name) }
  • I can't see why we can not do this with language support.,因为实现了接口A,所以必须“定义”公共方法test()。但是,您可以覆盖它,使其不执行任何操作,但您必须实现它,因为您说 B 是 A 的子类型。
猜你喜欢
  • 2013-03-16
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多