首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按值从枚举中选择对象

按值从枚举中选择对象
EN

Stack Overflow用户
提问于 2022-04-14 08:42:38
回答 1查看 60关注 0票数 0

我要上一节文言文课。根据值的不同,我需要选择一个服务(在getMessage函数中)。

代码语言:javascript
复制
interface MyService<K, V> {
    fun message(): V
}

@Service
class FirstService : MyService<String, String> {
    override fun message(): String {
        return "It's first service"
    }
}

@Service
class SecondService : MyService<Long, Long> {
    override fun message(): Long {
        return 3
    }
}

enum class ServiceType {
    FIRST,
    SECOND
}

@Service
class Handler(
    @Autowired val firstService: MyService<String, String>,
    @Autowired val secondService: MyService<Long, Long>
) {

    fun sayMessage() {
        println(getMessage(ServiceType.FIRST))
        println(getMessage(ServiceType.SECOND))
    }

    private fun getMessage(type: ServiceType) = when (type) {
        ServiceType.FIRST -> firstService
        ServiceType.SECOND -> secondService
    }.message()
}

有没有办法不用whenif重写这段代码?

代码语言:javascript
复制
when (type) {
        ServiceType.FIRST -> firstService
        ServiceType.SECOND -> secondService
    }
EN

回答 1

Stack Overflow用户

发布于 2022-04-14 09:00:24

在您的情况下,我不认为有任何方法可以摆脱这种“时间”,因为服务是注入的,不能在枚举中构建。

如果要获得的值可以在枚举中创建或引用,则可以在其中添加一个抽象服务属性,并在每个枚举(第一和第二)中覆盖该属性:

例如:

代码语言:javascript
复制
enum class ServiceType {
    FIRST {
        override val service: MyService<*, *> = FirstService()
    },
    SECOND {
        override val service: MyService<*, *> = SecondService()
    };

    abstract val service: MyService<*,*>
}

你可以这样用它:

代码语言:javascript
复制
    private fun getMessage(type: ServiceType) = type.service.message()

同样,在您的具体情况下,您不能使用这种方法。

在我看来,这是唯一的方法来摆脱一个时间或如果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71868826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档