Open postfixNotation opened 3 weeks ago
How about
aMaybe.toOption().map { it as ASub }
(aMaybe as? ASub).toOption()
Good and helpful ideas, but if you have many type checks you might still end up with lots of boilerplate. Reducing boilerplate was probably also the intention of Arrow's toOption
method on nullable types.
The first proposal might throw a ClassCastException
as far as I know.
I'm not sure that this belongs to Arrow, to be honest. I don't think the pattern of moving to Option
+ making a subtype check is widely used (this is the first time I hear about it, in fact). I think that some of the options raised by @hoc081098 (like (x as? T).toOption()
are much clearer than x.toOption<T>()
.
Arrow provides this handy
public fun <T> T?.toOption(): Option<T> = this?.let { Some(it) } ?: None
extension function which converts nullable types toOption
dtos.There are some use cases I have where having this functionality for subtype checks is pretty handy replacing imperative is-checks.
I guess it's clear what I'm trying to say. The above is just an illustration to depict my thoughts.