Is there a way to access an instance variable from...
# getting-started
e
Is there a way to access an instance variable from an inner class of a sealed class? Here’s a code excerpt:
Copy code
class NearbyConnection{

    var connectionsClient: ConnectionsClient = Nearby.getConnectionsClient(context)
    
    public sealed class ConnectionState(val name: String) {
        inner class Authenticating: ConnectionState("authenticating") {
            fun accept() {
                connectionsClient.acceptConnection(neighborId, payloadCallback)
                updateState(ConnectionState.Connecting(neighborId, neighborName))
            }
        }
I am getting the error “unresolved reference connectionsClient” within the function.
k
Your sealed class should be inner too.
e
I get the error:
Modifier 'inner' is incompatible with 'sealed'
.
k
That's strange, why would that be? Then I'm afraid you're stuck, but it's not that difficult to write out the "inner" boilerplate yourself, just add a parameter for the outer class instance.
e
True, I’ll have to think about whether it’s worth it. (I only want the method to be callable when the connection is in the
Authenticating
state.)
Thank you @karelpeeters
k
Ah it's because sealed classes can only be top level for the "subclass must be in the same file" rule: https://discuss.kotlinlang.org/t/sealed-inner-classes/2371
k
I’d pass
ConnectionsClient
instance through API (
accept
function in your case) instead of relying on inner state
e
@Kirill Zhukov The
ConnectionState
gets passed to a client who should not need to know about the
ConnectionsClient
.