在Java中你可以有:
final Map<String, Supplier<Interface>> associations = new HashMap<>();
associations.put("first", One::new);
associations.put("second", Two::new);
Run Code Online (Sandbox Code Playgroud)
在 Kotlin 中,这翻译为:
val associations: MutableMap<String, Supplier<Interface>> = HashMap()
associations["first"] = Supplier(::One)
associations["second"] = Supplier(::Two)
Run Code Online (Sandbox Code Playgroud)
如果没有kotlin-reflect
,这是唯一的方法还是我错过了什么?恕我直言,这看起来不太好或 Kotlinish。
由于有人发生推理错误,这是完整的代码:
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
Run Code Online (Sandbox Code Playgroud)
更kotlinish 的替代方案可能是
val associations: MutableMap<String, Supplier<out Interface>> = hashMapOf(
"first" to Supplier(::One),
"second" to Supplier(::Two)
)
Run Code Online (Sandbox Code Playgroud)
associations
如果没有在其他地方进行修改,则可能不再需要可变。
并将供应商替换为 kotlin 高阶函数
val associations: Map<String, () -> Interface> = hashMapOf(
"first" to ::One,
"second" to ::Two
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1079 次 |
最近记录: |