y
01/04/2023, 4:52 AMplus
overload with Kotlin pattern matching?
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` :
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)
}
ephemient
01/04/2023, 5:13 AMoperator fun plus(rhs: MyType) =
if (this is A && rhs is A) {
A(this.amount + rhs.amount)
} else {
B
}
y
01/04/2023, 5:14 AMy
01/04/2023, 5:16 AMwhen
(because of Kotlin’s smart casting making it very ergonomic), I would still like to know if the pattern matching way is possibleephemient
01/04/2023, 5:16 AMif
aren't equivalent now. I think this is similar to https://youtrack.jetbrains.com/issue/KT-10461ephemient
01/04/2023, 5:16 AMwhen
inside another when
ephemient
01/04/2023, 5:19 AMoperator 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 ity
01/04/2023, 5:21 AM