Declaration site variance problem


#1

Hi friends

In funKTionale I use declaration-site variance for Option and Either types

https://github.com/MarioAriasC/funKTionale/blob/master/src/main/kotlin/org/funktionale/option/Option.kt

In M10 the compiler is marking this as an error

public fun getOrElse(default: () -> T): T {
    return if (isEmpty()) {
        default()
    } else {
        get()
    }
}

The error is "Error:(41, 41) Kotlin: Type parameter T is declared as 'out' but occurs in 'in' position in type () -> T"

Technically that “T” is an “out” 'cause is the return of “default” function… an out.

Am I right or I missing somethig?


#2

The compiler is right: taking a function that returns T is equivalent to taking a T. Allowing such methods would have made it possible to get an exception at runtime.

I’d suggest using extension functions in this case


#3

If that was the case, it would be possible to workaround these compiler errors by changing parameter of type T to the parameter of a functional type returning T, wouldn't it? :)

In fact ‘default’ is in a contravariant (in) position, and covariant (out) of contravariant is still contravariant


#4

Thanks for the idea