Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

["Request"] Declarative (sub-)type checks yielding Option<*> #3493

Open
postfixNotation opened this issue Sep 30, 2024 · 3 comments
Open

["Request"] Declarative (sub-)type checks yielding Option<*> #3493

postfixNotation opened this issue Sep 30, 2024 · 3 comments

Comments

@postfixNotation
Copy link

Arrow provides this handy public fun <T> T?.toOption(): Option<T> = this?.let { Some(it) } ?: None extension function which converts nullable types to Option dtos.

There are some use cases I have where having this functionality for subtype checks is pretty handy replacing imperative is-checks.

sealed interface A
interface ASub : A

val aMaybe: A? = null

// This is what we have in Arrow already
val aOption: Option<A> = aMaybe.toOption()

// Option 1
val aSubOption: Option<ASub> = aProvider().toOption<ASub>()

// Option 2
//val aSubOption: Option<ASub> = aProvider().toOption<ASub, A>()


// Option 1
inline fun <reified T> Any?.toOption(): Option<T> = (this as? T)?.let { Some(it) } ?: None

// Option 2
//inline fun <reified S : T, T> T?.toOption(): Option<S> = (this as? S)?.let { Some(it) } ?: None

fun aProvider(): A {
    return object : ASub {}
}

I guess it's clear what I'm trying to say. The above is just an illustration to depict my thoughts.

@hoc081098
Copy link
Contributor

hoc081098 commented Sep 30, 2024

How about

  • aMaybe.toOption().map { it as ASub }
  • (aMaybe as? ASub).toOption()

@postfixNotation
Copy link
Author

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.

@serras
Copy link
Member

serras commented Oct 15, 2024

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>().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants