Kotlin function as map value

Viewed 598

In Java you can have:

final Map<String, Supplier<Interface>> associations = new HashMap<>();
associations.put("first", One::new);
associations.put("second", Two::new);

In Kotlin this translates to:

val associations: MutableMap<String, Supplier<Interface>> = HashMap()
associations["first"] = Supplier(::One)
associations["second"] = Supplier(::Two)

Without kotlin-reflect, is this the only way or am I missing something? That doesn't look so good or Kotlinish imho.

Since someone occurred in inference errors, this is the complete code:

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
2 Answers

The more kotlinish alternative might be

val associations: MutableMap<String, Supplier<out Interface>> = hashMapOf(
    "first" to Supplier(::One), 
    "second" to Supplier(::Two)
)

associations may not need to be mutable anymore as well if it isn't modified anywhere else.

And replacing Supplier with a kotlin high-order function

val associations: Map<String, () -> Interface> = hashMapOf(
    "first" to ::One,
    "second" to ::Two
)

Assuming you don't necessarily need an instance of Supplier but rather just a new function, you could go with either of those versions

val associations: MutableMap<String, () -> Interface> = HashMap()
associations["first"] = { One() }
associations.set("second") { Two() }

They are not perfect but look better than Supplier(::One) IMHO.

Related