samedi 9 janvier 2021

Kotlin Map with classes as keys?

I've got an interface Vehicle with implementations Car, Motorcycle, Skateboard, etc.

I would like to create a Map that contains attributes or data values for each implementation. A very simple one would look like:

val vehicleInfo : Map<KClass<Vehicle>, Map<String, String>> mapOf(
  Car::class to mapOf("wheels" to "4", "license_required" to "true"),
  Motorcycle::class to mapOf("wheels" to "2", "license_required" to "true"),
  Skateboard::class to mapOf("wheels" to "4", "license_required" to "false"),
)

but this won't compile due to Type Mismatch (between the KClass keys and KClass<Vehicle>)

(a similar possibility would be to use a data class for the map values: data class(val wheels : Int, val license_required : Boolean))

Is there a way to create a Map with classes as the keys? Alternatively, is there a better pattern for creating a 1-1 mapping between classes and attributes (I don't want to say "properties" because, obviously, I could define these as properties in the interface and provide values in each class definition -- I specifically do NOT want to do that, I want to keep all the attributes together in its own Map or maybe some other data structure)... it seems like some functional programming concept or higher-order function might be applicable here. Thank you.





Aucun commentaire:

Enregistrer un commentaire