How to map a data type for a dataset of this data type

Code:

abstract class DataContainer(public val path: String)
val preloaded: MutableMap<Class<out DataContainer>, HashSet<out DataContainer>> = hashMapOf()

I would like to know how to make Kotlin understand that the first out DataContaineris the same type as the second out DataContainer.
So a code like:

fun <D: DataContainer> get(clazz: Class<D>): HashSet<D> = preloaded[clazz] as HashSet<D>

It does not require as HashSet<D>(and is not subject to cast errors). I am new to Kotlin, so give a link to the documentation if I missed something. In addition, this code will be inside objectif it matters.

+6
source share
2 answers

I don’t think that what you want is possible at the language level.

get , . , , - put.

, D : DataContainer Set<D>, . , - :

object DataContainerRegistry {

    private val preloaded: MutableMap<Class<out DataContainer>, HashSet<DataContainer>> = hashMapOf()

    fun put(dataContainer: DataContainer) {
        val set = preloaded.getOrDefault(dataContainer::class.java, HashSet())
        set.add(dataContainer)
        preloaded[dataContainer::class.java] = set
    }

    fun <D : DataContainer> get(clazz: Class<D>) = preloaded.getOrDefault(clazz, HashSet()) as Set<D>

}

:

  • (DataContainerRegistry singleton ) preloaded
  • get Set, .

, , preloaded Set, , .

+1

Java.

, , Animal. Cat Dog, Cat , , Cat .

, , Cat Dog, .

, , :

abstract class DataContainer(public val path: String)

abstract class CatDataContainer(path: String): DataContainer(path)

abstract class DogDataContainer(path: String): DataContainer(path)

DataContainer .

, , :

class TypedContainerHolder1<D: DataContainer> {

    val preloaded: MutableMap<Class<out D>, HashSet<out D>> = hashMapOf()

    fun get(clazz: Class<D>): HashSet<out D>? = preloaded[clazz]
}

val typedContainerHolder1 = TypedContainerHolder1<CatDataContainer>()

, , , , /. .

class TypedContainerHolder2<D: DataContainer> {

    inner class PreloadedMap<MapType : D> : Map<Class<out MapType>, HashSet<out MapType>> by hashMapOf()

    private val preloaded = PreloadedMap<D>()

    fun get(clazz: Class<D>): HashSet<out D>? = preloaded[clazz]
}

val typedContainerHolder2 = TypedContainerHolder2<DogDataContainer>()

, . , .

0

All Articles