Posts

Showing posts from November, 2025

Java Try monad using java 17 sealed interfaces

One pattern I find very effective is using sealed interfaces or classes. They work really well in place of Enum because the trait can define an implementation and the compiler can ensure that if a switch (java) or match (scala) statement references the type that every possible type is handled.   Lets look at an implementation of the Try monad that just  landed in maven central  . For those not familiar with scala's Try .   val dividend = Try ( StdIn .readLine( "Enter an Int that you'd like to divide:\n" ).toInt) val divisor = Try ( StdIn .readLine( "Enter an Int that you'd like to divide by:\n" ).toInt) val problem = dividend.flatMap(x => divisor.map(y => x/y)) problem match { case Success (v) => println( "Result of " + dividend.get + "/" + divisor.get + " is: " + v) Success (v) case Failure (e) => println( "You must've divided by zero or entered something that...