Runtime polymorphism in Kotlin

喜欢而已 提交于 2019-12-08 03:27:58

问题


Is there any elegant way to apply polymorphism in this case? The parser provides the following classes at runtime:

class io.swagger.v3.oas.models.media.Schema //is parent of the rest :

class io.swagger.v3.oas.models.media.ComposedSchema
class io.swagger.v3.oas.models.media.ArraySchema
class io.swagger.v3.oas.models.media.StringSchema
class io.swagger.v3.oas.models.media.ObjectSchema

I'd like to have function for each class with the same name and simple, short method which will cast and call necessary function at runtime. Which is actually happening, but I hope there is more brief solution, without necessity of making this kind of duplicates:

fun main() {

    val parser = OpenAPIV3Parser()
    val asList = listOf(pathYaml3, pathYml2)
    val map = asList.map(parser::read)
            .flatMap { it.components.schemas.values }
            .forEach(::parseRawSchema)
}


fun parseRawSchema(schema: Schema<Any>) {

    if (schema is ComposedSchema) {
        parseSchema(schema)
    }
    if (schema is StringSchema) {
        parseSchema(schema)
    }
...
}

fun parseSchema(schema: ComposedSchema) {
    println("Compose-schema")
}

fun parseSchema(schema: StringSchema) {
    println("Sting-schema")
}

...


回答1:


Try use extension. For example:

fun ComposedSchema.parseSchema() {
    println("Compose-schema")
}

fun StringSchema.parseSchema() {
    println("Sting-schema")
}

And than:

fun parseRawSchema(schema: Schema<Any>) {
    schema.parseSchema()
}



来源:https://stackoverflow.com/questions/57228391/runtime-polymorphism-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!