Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How can i return different types from my method?

I have this method.

    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
    }

How can i change this method to return the correct type?

like image 559
Israel Rodrigues Avatar asked Nov 22 '17 21:11

Israel Rodrigues


Video Answer


1 Answers

It's hard to give you a difinitive answer without you giving more info, but the easiest way to return multiple types is to have them all share an interface or superclass:

interface Offer

class Addon : Offer
class Sale : Offer
class Plan : Offer
class CustomPlan : Offer

You can also use a sealed class if your options are static, it just depends on your use case. Either way, you can then just have the function return type be Offer

For more information see:

  • Interfaces
  • Sealed Classes
like image 97
bj0 Avatar answered Oct 11 '22 10:10

bj0