lennertr
lennertr

Reputation: 150

Variable can be of two different types

I'm working on a use case where I use the ECB Loan Data Templates. The problem I ran into is, that variables can be of two different types. E.g. the field "Date of the Financial Statements at Underwriting" can be of type Date and also of type NoData which is a Enum. How can I construct this in Kotlin?

I'm looking for something like:

val dateOfTheFinancialStatementsAtUnderwriting: Date || NoData

Would a custom class which wraps these two types be a proper way to handle this?

Thanks in advance for any help!

Upvotes: 2

Views: 1202

Answers (1)

JavierSA
JavierSA

Reputation: 801

As @kris_k says, you can use the data type Either. If you don't want to add a library (Arrow), you can define it yourself with a sealed class:

sealed class Either<out L, out R> {

    data class Left<out L>(val a: L) : Either<L, Nothing>()

    data class Right<out R>(val b: R) : Either<Nothing, R>()

    val isLeft: Boolean get() = this is Left<L>
    val isRight: Boolean get() = this is Right<R>
}

How to return an Either:

class Date
class NoData

fun getDateOfTheFinancialStatementsAtUnderwriting(): Either<NoData, Date> {
    if (...) {
        return Either.Left(NoData())
    } else {
        return Either.Right(Date())
    }
}

How to use the Either:

val result: Either<NoData, Date> = getDateOfTheFinancialStatementsAtUnderwriting()

when (result) {
    is Either.Left -> {
        val noData: NoData = result.a
        TODO()
    }
    is Either.Right -> {
        val date: Date = result.b
        TODO()
    }
}

Upvotes: 2

Related Questions