Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the getOrElse() function of arrow-kt returning Any?

I am trying to understand the getOrElse() function of arrow-kt. I want to create a simple function that takes a list of strings, filters them, and returns the first matching value as an Option<String>. I created the following trivial example:

fun filterStrings(incoming: List<String>): Option<String> {
    val result = incoming.filter {
        it.contains('e')
    }.firstOrNone().getOrElse {
        incoming.filter {
            it.contains('b')
        }.firstOrNone()
    }

    return result
}

@Test
fun `test filter strings`() {
    val values = listOf("aad", "aba", "cdc", "bbb")
    val result = filterStrings(values)
    assertThat(result.isSome()).isTrue()
    assertThat(result.getOrBlank()).isEqualTo("aba")
}

In this example, the code will fail to compile since result is being smartcast to Any. Why is the result variable being smartcast to Any instead of Options<String>? Is there a way to work around this without doing an unsafe cast? I am aware that there are better ways to write a function like this, but I'm trying to get a handle on the fundamentals of what is happening.

like image 758
pbuchheit Avatar asked Dec 16 '25 11:12

pbuchheit


1 Answers

getOrElse unwraps an Option and returns its value, respectively the default you provided when the value is missing.

So the return type of getOrElse is the union of the Option's type - here String - and the type of the default value - here Option<String>. Their nearest common supertype is Any, so that's the type of the return value here.

The documentation describes it as follows:

Returns the option's value if the option is nonempty, otherwise return the result of evaluating default.

like image 178
Leviathan Avatar answered Dec 18 '25 23:12

Leviathan