is it an anti-pattern to use sealed classes/interfaces as an approximation of an algebraic data type? i've been doing things like below, but it seems that this causes
instanceof
checks -- so naturally various stack overflow answers mentioned "code smell", and i'm wondering if there's truth to that 🙂
Copy code
sealed class Node
data class Leaf(x: Int): Node()
data class Tree(left: Node, right: Node?): Node()
a
Alex Prince
10/18/2021, 7:04 PM
I do the same thing to get a DU type, it's really your only choice ( at least that I've found ) for that more functional style so far.
👍 1
c
conner
10/18/2021, 7:15 PM
it also seems like
instanceof
is much more optimized than it used to be, so maybe this is more FUD than anything
d
dmitriy.novozhilov
10/18/2021, 8:19 PM
Actually it's one of main usecases for sealed hierarchies
💯 5
s
Stephan Schroeder
10/19/2021, 6:51 AM
instanceof
-checks of normal classes in Java is a code smell,
is
-checks of sealed classes in Kotlin isn't. Mostly because the compiler can check that you covered all cases, I guess. (maybe also because of smart cast 🤔)