kotlinextension-methodsclass-visibility

Kotlin: Visibility modifier changes type of anonymous object


Removing the private modifier of myScope (line 4) in the following working code will break the code. The reason for that is the changing type of myScope. Is the visibility set to private the type is: anonymous object : Scope. Without private the type is switched to Scope. How can I fix this behavior?

interface Scope
operator fun<SD: Scope> SD.invoke(block: SD.() -> Unit) = block()

private val myScope = object : Scope {
    fun Int.myScopedExtFunction() = 1337
}

fun usage() {
    myScope {
        1.myScopedExtFunction()
    }
}

Here both versions in Android Studio: enter image description here


Solution

  • This behavior is by design. See the documentation:

    Note that anonymous objects can be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or Any if you didn't declare any supertype. Members added in the anonymous object will not be accessible.