logoalt Hacker News

ZeroClickOktoday at 10:44 AM1 replyview on HN

I understand what the author says, but in my experience, "Nullable Types" and "Open/Sealed Classes" are two different subjects and...

1) For "Nullable Types", I see that it is VERY good to think about if some type can be null or not, or use a type system that does not allow nulls, so you need some "unit" type, and appropriately handle these scenarios. I think it is ok the language enforces this, it really, really helps you to avoid bugs and errors sooner.

2) For "Open/Sealed Classes", my experience says you never (or very rarely) know that a class will need to be extended later. I work with older systems. See, I don't care if you, the original coder, marked this class as "sealed", and it does not matter if you wrote tons of unit tests (like the author advocates), my customer wants (or needs) that I extend that class, so I will need to do a lot of language hacks to do it because you marked as sealed. So, IMHO, marking a class as "open" or "sealed" works for me as a hint only; it should not limit me.


Replies

mh2266today at 2:35 PM

sealed classes are just retrofitting sum types onto the JVM. If Kotlin could have used "enum" for it then they probably would have, like Swift and Rust did.

The main point of sealed classes is exhaustive `when` expressions:

    return when (val result = something()) {
      Result.Success -> // ...
      Result.Failure -> // ...
    }
If another subclass appeared at runtime, then the code would fall off the end of that when expression.