1

我想从一个类中提供多个不同类型的不同代表。例如:

class A {
  val instanceOfB = B()

  val aNumber: SomeType by instanceOfB
  val anotherNumber: SomeOtherType by instanceOfB
}

class B {
  operator fun <T1: SomeType> getValue(thisRef: Any?, property: KProperty<T1>): T1 {
    return SomeType()
  }

  operator fun <T2: SomeOtherType> getValue(thisRef: Any?, property: KProperty<T2>): T2 {
    return SomeOtherType()
  }
}

open class SomeType {}
open class SomeOtherType {}

此示例给出以下编译器错误: 'operator' modifier is inapplicable on this function: second parameter must be of type KProperty<*> or its supertype

有没有办法指定泛型类型参数以便我可以实现这一点?

4

1 回答 1

1

只有这样我才能编译和运行它,尽管我强烈建议不要在概念证明之外使用它,因为 inline 会生成大量垃圾代码,并且每次getValue调用都将贯穿整个when语句:

class B {
  inline operator fun <reified T : Any>getValue(thisRef: Any?, property: KProperty<*>): T {
    return when(T::class.java){
        SomeType::class.java -> SomeType() as T
        SomeOtherType::class.java-> SomeOtherType() as T
        else -> Unit as T
    }
  }
}

还有operator fun provideDelegate生成委托的,但它也限制为 1 个返回值。我不认为有优雅/受支持的方式来做你现在需要的事情。

于 2018-06-28T00:09:45.760 回答