是否可以通过单个 class 提供多种委托类型?

Is it possible to provide multiple delegate types with a single class?

我想从单个 class 中提供多个不同类型的委托。例如:

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

有没有什么方法可以指定泛型类型参数,这样我就可以做到这一点?

我编译它的唯一方法和 运行,尽管我强烈建议除了概念验证之外不要使用它,因为内联会生成大量垃圾代码,并且每个 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 个 return 值。我不认为有优雅/支持的方式来做你现在需要的事情。