https://kotlinlang.org logo
Title
k

Kumaran Masilamani

05/10/2019, 7:41 PM
Can anyone help me to do a pattern match on ADT?
//Given my ADT as follows ...
sealed class Result {
    object Success  : Result()
    data class Failure(val reason: FailureReason) : Result()
    enum class FailureReason { REASON1, REASON2 }
}
//I want to do something like this
when (result) {
            is Success -> 
            is Failure(REASON1) -> 
            is Failure(REASON2) -> 
        }
In Scala I will use with a variable, but it didn't work in Kotlin
m

Mike

05/10/2019, 7:45 PM
Kotlin doesn’t support pattern matching. Hopefully it’s a yet as Java is looking to start adding pattern matching to
switch
Also, I don’t see
SaveFailed
as an element of your Result sealed class. Typo/oversight on your part, or something I don’t understand?
k

Kumaran Masilamani

05/10/2019, 7:48 PM
Sorry the
SaveFailed
was a typo. Please read as
Failure
Thank you for your response. I will try to change as an individual type for now.
This link shows an example to get the value inside the type.
<https://medium.com/sharenowtech/kotlin-adt-74472319962a>
fun showDeliveryStatus(status: DeliveryStatus) {
  return when (status) {
    is Preparing -> showPreparing()
    is Dispatched -> showDispatched(it.trackingNumber) // note that no cast needed!
  }
}
Any thoughts?
m

matt tighe

05/10/2019, 8:14 PM
you’re looking for
when (result) {
    is Success -> { ... }
    is Failure -> {
        when (result.reason) {
            REASON 1 -> { ... }
            REASON 2 -> { ... }
         }
    }
}
IMO i like this structure better:
sealed class Result
data class Success : Result()

sealed class Failure : Result()
data class FailureType1: Failure()
data class FailureType2: Failure()

when (result) {
    is Success -> { handleSuccess(result) }
    is Failure -> { handleFailure(result) }
}

fun handleFailure(failureType: Failure) {
    when (failureType) {
        is FailureType1 -> { … }
        is FailureType2 -> { … }
    }
}
you get compile time checking of type exhaustion as long as you assign the when statements to variables or return them in this case
k

Kumaran Masilamani

05/10/2019, 8:33 PM
That looks like a better solution. Cheers.