4 ms·
This is great news! I was also kind of surprised to see the article talking about algebraic data types... table stakes for ADTs is sum types and I have missed
by crdrost 5y ago
This is great news!
I was also kind of surprised to see the article talking about algebraic data types... table stakes for ADTs is sum types and I have missed them considerably in the Java ecosystem.
Kotlin has something like them with sealed classes, although I'm a newcomer to the Kotlin and Spring Boot ecosystem so I don't see explicitly how I make some simple case like JSON
{"type": "left", "abc": 123}
{"type": "right", "def": "456"}
turn into some structure like:
sealed class EitherTest {
data class Left(val abc: Long): EitherTest()
data class Right(val def: String): EitherTest()
}
rather than the hacky version that you have to do in relational databases and Java which don't support such things,
enum class EitherType { LEFT, RIGHT }
data class EitherTest(val type: EitherType, val abc: Int?, val def: String?)
Like I’m not saying that there’s no way, I’m sure there’s a way... just that the ecosystem seems so hesitant to embrace sum types that like the above sealed class is widely viewed as a hack and there is no statement about “here is how you actually use sum types for everything in your Spring application with Kotlin.”
Was gonna give the choose-your-own-adventure example of why sum types are handy and how you have to kind of hack around them with inheritance when you don't have them but it occurs to me that anyone who has stuck with this comment this far probably already has some familiarity with this?
- oftenwrong 5y agoSealed classes are (most likely) going to be in the next version of Java, Java 17: https://openjdk.java.net/jeps/409 https://openjdk.java.net/jeps/409
- TJSomething 5y agoIn traditional Java, you're probably using Jackson for your JSON. You can achieve those sorts of results by specifying the classes and type tags in annotations on an abstract Either class to use Jackson's polymorphic serialization feature.
- balefrost 5y agoThe point of sealed classes is that you have a known number of possible representations. So you can have `when` blocks that exhaustively check all possibilities. Having an open class hierarchy would not work for that purpose.
- __jem 5y agothis technique works with sealed classes, i’ve done it before. it throws a runtime exception if it can’t identify the discriminant.
- aphexairlines 5y agoYou do it like this: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#sealed-classes https://github.com/Kotlin/kotlinx.serialization/blob/master/...
- winrid 5y agoThe easiest way is with GSON: https://mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ https://mkyong.com/java/how-do-convert-java-object-to-from-j... You would just have to have annotations on the enum names to get the lowercase values in your example json.