在Java中,您可以拥有:
final Map<String, Supplier<Interface>> associations = new HashMap<>();
associations.put("first", One::new);
associations.put("second", Two::new);
在 Kotlin 中,这意味着:
val associations: MutableMap<String, Supplier<Interface>> = HashMap()
associations["first"] = Supplier(::One)
associations["second"] = Supplier(::Two)
没有使用kotlin-reflect
,这是唯一的方法还是我遗漏了什么?在我看来,这看起来不太好,也不符合Kotlin的风格。
由于出现了推断错误,这是完整的代码:
fun example() {
val associations: MutableMap<String, Supplier<Interface>> = HashMap()
associations["first"] = Supplier(::One)
associations["second"] = Supplier(::Two)
}
interface Interface
class One : Interface
class Two : Interface
Interface
和One
/Two
是如何定义的?你尝试过像associations["first"] = { One }
这样的东西吗? - msrd0Supplier<out Interface>
才能使其正常工作。 - msrd0{ One() }
对我来说看起来很好。 - Abhijit Sarkar