Kotlin - 我如何从我的方法中返回不同的类型?

Isr*_*ues 2 generics kotlin

我有这个方法.

    private fun getOffer(offers: OfferRepresentation, type: OfferType): ???? {
    return when (type) {
        OfferType.ADDON -> offers.addon 
        OfferType.SALE -> offers.sale
        OfferType.PLAN -> offers.plan
        OfferType.CUSTOMPLAN -> offers.customPlan
    }
Run Code Online (Sandbox Code Playgroud)

如何更改此方法以返回正确的类型?

bj0*_*bj0 6

如果没有提供更多信息,很难给出一个不同的答案,但返回多种类型的最简单方法是让它们共享一个接口或超类:

interface Offer

class Addon : Offer
class Sale : Offer
class Plan : Offer
class CustomPlan : Offer
Run Code Online (Sandbox Code Playgroud)

sealed class如果你的选项是静态的,你也可以使用它,它只取决于你的用例.无论哪种方式,您都可以使用函数返回类型Offer

有关更多信息,请参阅


Eke*_*eko 6

Any您有使用作为返回类型的简单解决方案。Any与 Java 中的不完全一样Object,但在本例中已经足够接近了(https://kotlinlang.org/docs/reference/classes.html):

Kotlin 中的所有类都有一个公共超类Any,这是未声明超类型的类的默认超类:

class Example // Implicitly inherits from Any
Run Code Online (Sandbox Code Playgroud)

因此,如果您的返回类型完全不相关,并且让它们共享一个公共接口对您来说没有意义,那么您可以使用 Any:

private fun getOffer(offers: OfferRepresentation, type: OfferType): Any {
    return when (type) {
        OfferType.ADDON -> offers.addon 
        OfferType.SALE -> offers.sale
        OfferType.PLAN -> offers.plan
        OfferType.CUSTOMPLAN -> offers.customPlan
    }
Run Code Online (Sandbox Code Playgroud)


小智 -2

JVM 不能从函数返回超过 1 个值。您可以做的是返回一个对或元组,或者创建一个包含所有字段的数据类,然后将它们作为可选字段

例如:

数据类 Offer(val type1: String?=null, val type2: Integer? = 0)