Search code examples
kotlinarrow-kt

Kotlin arrow.kt - Option.getOrElse is accepting other type than T


I am trying to use the Option.getOrElse() method.

According to the source:

inline fun <R> fold(ifEmpty: () -> R, ifSome: (A) -> R): R = when (this) {
  is None -> ifEmpty()
  is Some<A> -> ifSome(t)
}

fun <T> Option<T>.getOrElse(default: () -> T): T = fold({ default() }, ::identity)

But when I call getOrElse with a lambda that returns a value of type other than type T, it does not show any error compile time or runtime.

val value1 = Some("val")

// No error
value1.getOrElse { true }

It does not seem right. What am I doing wrong?


Solution

  • This is because Option is covariant (you can see it's declared as Option<out A>), so value1 is also an Option<Any> and { true } is inferred to be () -> Any.