LppEdd
LppEdd

Reputation: 21172

Kotlin function as map value

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

Upvotes: 5

Views: 1313

Answers (2)

Trevor
Trevor

Reputation: 1451

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
)

Upvotes: 4

msrd0
msrd0

Reputation: 8430

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.

Upvotes: 1

Related Questions