Just a raw thought: ```sealed class A class X : A...
# announcements
c
Just a raw thought:
Copy code
sealed 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
Copy code
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:
Copy code
Service {
  fun returnSomething(a: A) = a.returnSomething()
}
Anytime you find yourself writing code of the form "if the object is of type
T1
, then do something, but if it's of type
T2
, then do something else," slap yourself!
— Scott Meyers, Effective C++
m
It's very helpful for State Machine type processing. Defines the concrete states something can be in, and avoids flags on an object with nested 'if-else' statements to determine state and next step. More explicit way of accomplishing same thing, with assistance from the Compiler. If using as a 'wrapper' for classes, then agree that polymorphism is better. i.e. common function that gets called.
c
Aha, I see. I guess this should be documented, because I find the example I've illustrated in lots of places.
people are very happy they can now substitute
if(a instanceOf X) ... else if (a instanceOf Y)
with a
when (a) { is X -> ...; is Y -> ...}
At least it's more readable 😄
b
The
when(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.
k
but what if the logic doesn't belong to those classes? you either do visitor or this, right?
👌 1