Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 4
    Jörg, I feel like your example is flawed. In Scala a sealed trait basically corresponds to a Java enum (which can also have behaviour). So it is nice that you can do that in Scala - but sealed trait is imho just another word for a java enum - what do you think? Commented Sep 18, 2013 at 11:50
  • 1
    I have to agree with @Falcon. In fact, it's possible to write idiomatic Java code that looks a lot like those sealed traits... only using Enums and overriding toString(), much like you did. No need to use switch with enums, either! If you must use switch, Enums in Java help with pseudo-"pattern matching": the compiler will warn you if you are missing "patterns". Commented Sep 18, 2013 at 14:09
  • 1
    + You can iterate over enums whereas it's a bit harder and noisier to do the same thing with traits Commented Sep 18, 2013 at 14:15
  • My concern with this would be efficiency. Passing an object reference around might well be as fast as passing an enumeration around and only incur a slight extra overhead for marking those addresses as used, but I question whether dynamic method dispatch would be as fast as a switch. If nothing else, I expect having 7 toString methods compiled down (to e.g. bytecode or machine code) would use more memory space than a single function with a switch. The difference is probably negligable on a big modern processor, but on an embedded system it might be significant... Commented Feb 3, 2024 at 5:45
  • ... Though to be fair, one advantage of the dynamic method approach is that more values can be added at runtime. Though I suspect the cases where that would actually be useful are somewhat limited. Commented Feb 3, 2024 at 5:47