-
-
Save abergfeld/6f29c9103c8cc30be0eb94a5e2fe40c9 to your computer and use it in GitHub Desktop.
Coproduct3 Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun coproductTesting() { | |
val validCoproductA = "1.00".cop<String, Long, Float>().print() //Coproduct3(value=1.00) | |
val validCoproductB = 4.00f.cop<Long, String, Float>().print() //Coproduct3(value=4.0) | |
val validCoproductC = 9001L.cop<Long, Float, String>().print() //Coproduct3(value=9001) | |
val validDuplicateType = "String".cop<String, String, String>().print() //Coproduct3(value=String) | |
validCoproductA.select<String>().print() //Some(1.00) | |
validCoproductA.select<Long>().print() //None | |
validCoproductA.select<Float>().print() //None | |
//validCoproductA.select<BigDecimal>() //Doesn't compile | |
validCoproductB.select<String>().print() //None | |
validCoproductB.select<Long>().print() //None | |
validCoproductB.select<Float>().print() //Some(4.0) | |
//validCoproductB.select<BigDecimal>() //Doesn't compile | |
validCoproductC.select<String>().print() //None | |
validCoproductC.select<Long>().print() //Some(9001) | |
validCoproductC.select<Float>().print() //None | |
//validCoproductC.select<BigDecimal>() //Doesn't compile | |
validDuplicateType.select<String>().print() //Some(String) | |
//validDuplicateType.select<Unit>() //Doesn't compile | |
validCoproductA.value //So we can still pull out the value but it's Any? so it's pretty well useless to do so | |
//We can't make it an internal val because we need reified generics for the methods that operate on it | |
val foldedBigDecimal = validCoproductA.fold( | |
{ BigDecimal(it) }, //Actual value | |
{ BigDecimal(it) }, | |
{ BigDecimal(it.toInt()) } | |
).print() //1.00 | |
// val foldedBigDecimal = validCoproductA.fold( | |
// { BigDecimal(it) }, | |
// { BigDecimal(it) }, | |
// { BigDecimal(it) } //Doesn't compile, no constructor for BigDecimal(Float) | |
// ) | |
val mappedCoproductB = validCoproductB.map( | |
{ "LongValue: $it" }, | |
{ BigDecimal(it) }, | |
{ it * 2 } //Actual value | |
).print() //Coproduct3(value=8.0) | |
//Types are preserved from maps returned value | |
mappedCoproductB.fold( | |
{ it }, | |
{ it.abs().toString() }, | |
{ it.dec().toString() } | |
).print() //7.0 | |
} | |
private fun <T> T.print(): T { | |
System.out.println(this) | |
return this | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment