Hi guys, I have a sealed class S in another class ...
# getting-started
s
Hi guys, I have a sealed class S in another class V with subtypes of the sealed class defined in it. How can I access methods of V in the subtypes?
Copy code
class V {
    fun doSomething() {
        ...
    }

   sealed class S {
         object S1: S() {
             // how can I possibly do below:
             init {
                  doSomething()
             }
         }
   }
}
I know for a regular class, I just need to declare it as inner and call the regular outer class methods from it
m
Could you provide a minimal example that demonstrates your problem?
s
updated @marstran
m
You can't make a sealed class an inner class. Also, an inner class cannot be an
object
, because the object needs a reference to an instance of the outer class (so you would need one singleton object for every instance of V, which is contradictory).
But do you have to make it an inner class? You could do something like this:
Copy code
class V {
    fun doSomething() {
        ...
    }
}

sealed class S(val v: V) {
    class S1(v: V): S(v) {
        init {
            v.doSomething()
        }
    }
}
s
Thanks @marstran, your example above is clever. Modified to suit my need.
Copy code
class V {
    fun doSomething() {
        ...
    }

   sealed class S {
         class S1(v: V): S() {
             init {
                  v.doSomething()
             }
         }
   }
}
👍 1