Skip to content

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

@postfixNotation

Description

@postfixNotation

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions