Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

generics - Kotlin: generate a Factory by class

We're trying to do some generic processing in kotlin. Basically, for a given class, we want to get the related Builder object. i.a. for any object that extends a GenericObject, we want a Builder of that Object.

interface Builder<T : GenericObject> 
object ConcreteBuilder: Builder<ConcreteObject>

We'd need a function that will return ConcreteBuilder from ConcreteObject

Our current implementation is a Map:

val map = mapOf<KClass<out GenericObject>, Builder<out GenericObject>>(
    ConcreteObject::class to ConcreteBuilder
)

Then we can get it with:

inline fun <reified T : GenericObject> transform(...): T {
    val builder = map[T::class] as Builder<T>
    ...

However this isn't very nice as:

  • we need an explicit cast to Builder<T>
  • the map has no notion of T, a key and a value could be related to different types.

Is there any better way to achieve it?

question from:https://stackoverflow.com/questions/65849484/kotlin-generate-a-factory-by-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A wrapper for the map could be:

class BuilderMap {

    private val map = mutableMapOf<KClass<out GenericObject>, Builder<out GenericObject>>()

    fun <T: GenericObject> put(key: KClass<T>, value: Builder<T>) {
        map[key] = value
    }
    
    operator fun <T: GenericObject> get(key: KClass<T>): Builder<T> {
        return map[key] as Builder<T>
    }
    
}

This hides the ugliness, while not completely removing it.

To use:

val builderMap = BuilderMap()
builderMap.put(ConcreteObject::class, ConcreteBuilder)
builderMap.put(BetonObject::class, BetonBuilder)
// builderMap.put(BetonObject::class, ConcreteBuilder) – will not compile

val builder = builderMap[T::class]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...