Kotlin中的运行时多态 [英] Runtime polymorphism in Kotlin

查看:102
本文介绍了Kotlin中的运行时多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,是否有任何优雅的方法来应用多态?解析器在运行时提供以下类:

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")
}

...

推荐答案

尝试使用扩展一个>. 例如:

Try use extension. For example:

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

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

比:

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

这篇关于Kotlin中的运行时多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆