is there any way to express this `plus` overload w...
# getting-started
y
is there any way to express this
plus
overload with Kotlin pattern matching?
Copy code
sealed class MyType {
    data class A(val amount: Int) : MyType()
    object B : MyType()

    operator fun plus(rhs: MyType) =
        when (this to rhs) {
            (A, B), (B, A) -> { B }
            (A, A) -> { A(this.amount + rhs.amount) }
        }
}
note, I’m aware that I can turn this into an
if
/`else` :
Copy code
operator fun plus(rhs: MyType) =
    if (this is B || rhs is B) {
        B
    } else {
        val lhsAmount = (this as A).amount
        val rhsAmount = (rhs as A).amount
        A(lhsAmount + rhsAmount)
    }
e
would be easier the other way around,
Copy code
operator fun plus(rhs: MyType) =
    if (this is A && rhs is A) {
        A(this.amount + rhs.amount)
    } else {
        B
    }
y
that’s true, thanks.
while in this case I definitely like this more than a
when
(because of Kotlin’s smart casting making it very ergonomic), I would still like to know if the pattern matching way is possible
e
it's unfortunate the two ways of using
if
aren't equivalent now. I think this is similar to https://youtrack.jetbrains.com/issue/KT-10461
no, not without nesting one
when
inside another
when
Copy code
operator fun plus(rhs: MyType) =
     when (this) {
         is A -> when (rhs) {
             is A -> A(this.amount + rhs.amount)
             B -> B
         }
         B -> B
     }
pretty ugly, I wouldn't recommend it
y
cool. much appreciated! also interesting to read about how Kotlin attempts to do flow-sensitive typing in the smart cast. I would honestly not expect it to be smart enough to deal with the case mentioned in the issue.