isnt sealed class take more memory than normal cla...
# announcements
c
isnt sealed class take more memory than normal class? considering O(k+m)
m
need more info what you are asking
c
what is the memory complexity of normal class compared to sealed class
m
classes have no
complexity
as far as I know. They are just a combination of pointers to their fields. sealed class is just a class with the added bonus that the compiler can know it's subclasses.
also I'm note sure what you mean with `cant use generic types' You can write: sealed class MyClass<T> just fine
c
well i meant the classes inside the sealed class
and i meant the instance of these classes , the space complexity.
r
Why do you think a sealed class takes more memory?
c
well afaik wont there be additional overhead for sealed class instance compared to normal class.
r
Again, why?
c
since the class has sub-class
m
sealed classes are a compilertime tool; on runtime there is afaik no difference between a class and a sealed class. There is no "knowing of it's subclasses" once you run the code.
well, one of the reasons could be that you just wanna enforce, on compile time that no other source can extend your class. Let's say you want to implement Operation
Copy code
sealed class Operation {
    class Add(val value: Int) : Operation()
    class Substract(val value: Int) : Operation()
    class Multiply(val value: Int) : Operation()
    class Divide(val value: Int) : Operation()
}
Now the compiler knows that Operation only has Add, Substract, Multiply and Divide. You can make an execute function e.g.:
Copy code
fun execute(x: Int, op: Operation) = when (op) {
    ...
    Operation.Increment -> x + 1
    Operation.Decrement -> x - 1
}
and you don't need to add an `else' statement and do something like: "Unknown subclass performing execute"
r
If you look at the generated byte code, Kotlin is adding the
else
clause for you (at least for a when expression), thus it's a compile time feature.