Kotlin 函数作为映射值

标签 kotlin

在 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/

相关文章:

kotlin - 如何使用 Kotlin 在 Jackson 中使用默认值和必需值控制 null 反序列化?

java - 如何像HID键盘一样通过蓝牙广播文本?

reflection - 如何通过反射在 Kotlin 中设置伴生对象的属性?

android - 膨胀第二个导航主机时,应用程序崩溃

kotlin - 第一次调用 `ArraysKt.contains` 很慢

kotlin - 如何在 Parcelable 中创建可为 null 的 bool 值

java - 升级到 Gradle 包装器到 7.0.2 和 JDK 11 后,Android 版本构建失败

spring-boot - Spring Boot Kotlin Mockito @MockBean 依赖在方法调用上抛出 IllegalStateException null

在集成测试的反射信息中不存在的测试中定义的 Kotlin 注释

android - 选中回收者 View 中的所有复选框