Czar
01/13/2020, 2:48 PMsealed class A
class X : A()
class Y : A()
class Z : A()
From what I've seen usually people do this to be able to write something like
class Service {
fun returnSomething(a: A) = when(a) {
is X -> /* ... */
is Y -> /* ... */
is Z -> /* ... */
}
}
Isn't it an illustration of an OOP anti-pattern, though?
Shouldn't it have been something along the lines of:
Service {
fun returnSomething(a: A) = a.returnSomething()
}
Anytime you find yourself writing code of the form "if the object is of type, then do something, but if it's of typeT1
, then do something else," slap yourself!T2
— Scott Meyers, Effective C++
Mike
01/13/2020, 3:03 PMCzar
01/13/2020, 3:07 PMCzar
01/13/2020, 3:09 PMif(a instanceOf X) ... else if (a instanceOf Y)
with a when (a) { is X -> ...; is Y -> ...}
At least it's more readable 😄Bob Glamm
01/13/2020, 3:15 PMwhen(a) { is X -> ... is Y -> ... }
is typical of sum types. The syntax is a little more useful with full-blown pattern matching (see Scala, Haskell for examples), but it provides concise syntax in the face of alternatives.kqr
01/13/2020, 3:50 PM