Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

See https://en.wikipedia.org/wiki/Tagged_union

In languages influenced by ML (like contemporary Java!) it is common in compiler work in that you might have an AST or similar kind of structure and you end up writing a lot of functions that use pattern matching like

   switch(node) {
      type1(a,b) -> whatever(a,b)
      type2(c) -> process(c)
   }
to implement various "functions" such as rewriting the AST into bytecode, building a symbol table, or something. In some cases you could turn this inside out and put a bunch of methods on a bunch of classes that do various things for each kind of node but if you use pattern matching you can neatly group together all the code that does the same thing to all the different objects rather than forcing that code to be spread out on a bunch of different objects.


OK yeah I see, that's natural to do with like rust enums

Java doesn't support this though I thought?


Currently Java supports records (finalized in JDK 16) and sealed classes (JDK 17) which together work as algebraic data types; pattern matching in switch was finalized in JDK 21. The syntax is pretty sweet

https://blog.scottlogic.com/2025/01/20/algebraic-data-types-...


oh thats cool. thanks for sharing!


> that's natural to do with like rust enums

Stands to reason. Rust "enums" are tagged unions (a.k.a. sum types, discriminated unions).

In implementation, the tag, unless otherwise specified, is produced by an enum, which I guess is why it got that somewhat confusing keyword.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: