在 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
,这是唯一的方法还是我错过了什么?这看起来不太好或 Kotlinish imho。由于有人发生推理错误,这是完整的代码:
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
最佳答案
更kotlinish的选择可能是
val associations: MutableMap<String, Supplier<out Interface>> = hashMapOf(
"first" to Supplier(::One),
"second" to Supplier(::Two)
)
associations
如果没有在其他任何地方修改,也可能不再需要可变。并用 kotlin 高阶函数替换供应商
val associations: Map<String, () -> Interface> = hashMapOf(
"first" to ::One,
"second" to ::Two
)
关于Kotlin 函数作为映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63163460/