Can't use lambdas with generic method because of SAM conversion limitations


#1

I seem to have run into the dreaded SAM conversion limitation (https://youtrack.jetbrains.com/issue/KT-7770) while writing something moderately complicated using higher order functions.

This is a simplified example that shows the problem:

interface Listy {
    fun <U> make(f: (Int) -> List<U>): List<U>
}

// Doesn't compile
val listy = Listy { f -> f(3) }

// Instead, this is needed :-(
val listy = object : Listy {
    override fun <U> make(f: (Int) -> List<U>): List<U> {
        return f(3)
    }
}

Unfortunately I believe this interface can’t be converted into a Kotlin function type (I think because higher rank types aren’t supported?) … and so I’m stuck with the ugly anonymous class syntax whenever I call it.

Unless anyone has a clever workaround…?