Could sealed classes help with this?

First off- if this post is a no-no, just let me know directly and I will delete it. I read the rules, but it wasn’t 100% clear if this type of post is allowed:

Second off – I think I’m just going to post the code and the test that demonstrates it. The TLDR is I’m looking for a kind of specific type of ‘Optional’ class.

Finally I might just be posting this to show off how darn clever I am, and I encourage you to put me back in my place. 😐

“` /* A class that encodes an Optional with a None type and a Something Type (called Filtered). The use case this was developed for was building runtime SQL queries. Usage should be obvious by looking at the tests included below. */ abstract class OptionalFilter { abstract val value: String companion object { fun reify(stringRepresentation:String): OptionalFilter { if (stringRepresentation == “”) { return NoFilter() } else { return Filtered(stringRepresentation) } } } }

// EG: “SELECT * from foo WHERE criteria = ${myFilter.value}” data class Filtered(val filter: String) : OptionalFilter() { override val value = filter }

/* EG: Nullify a WHERE filter where myFilter.value resolves to the empty string as in: ‘SELECT * from foo WHERE criteria = “”‘ */ class NoFilter : OptionalFilter() { override val value = “” } “`

@Test fun checkOptionalFilters() { assertEquals (Filtered("male").value, "male") assertEquals (NoFilter().value, "") assertTrue (OptionalFilter.reify("") is NoFilter) assertTrue (OptionalFilter.reify("female") is Filtered) assertEquals (OptionalFilter.reify("female").value, "female") }

submitted by /u/Place-Wide
[link] [comments]