https://kotlinlang.org logo
#language-evolution
Title
# language-evolution
z

zokipirlo

11/24/2023, 10:26 AM
Is it possible to somehow extract implementation of sealed classes to separate files and still use
SealedClass.InnerClass
syntax? For example:
Copy code
sealed class Message(val...) {
    class Text(...) : Message(...) {
        ...    
    }
    class Image(...) : Message(...) {
        ...    
    }
}

when (message) {
    is Message.Text -> ...
    is Message.Image -> ...
}
fun someFun(val msg: Message.Text) {}
But if I extract
Text
and
Image
to separete file from
Message
class file, because that file can be easiliy thounds of lines of code long, it would become:
Copy code
when (message) {
    is Text -> ...
    is Image -> ...
}

fun someFun(val msg: Text) {}
And when using those classes all around a project you lose hierarchy that
Text
is part of
Message
. I think it's still more pretty to use
Message.Text
. Could be possible somehow to combine best of both worlds?
h

hfhbd

11/24/2023, 10:31 AM
You could use an internal extension function instead.
z

zokipirlo

11/24/2023, 12:18 PM
How do you mean that?
w

Wesley Hartford

11/24/2023, 3:55 PM
I think @zokipirlo wants to be able to define the subclasses of a sealed class across several files, which is possible, but also keep them as nested classes of the parent (
Message
in the example case). Is that right? I don't think that's currently possible, but in theory I like the idea. In a lot of cases, it makes sense to use a sealed child class with a qualified syntax such as
Message.Text
, but if there are a whole lot of sub-classes, the file declaring them all could get unpleasantly large.
z

zokipirlo

11/24/2023, 8:14 PM
Yes, exactly that @Wesley Hartford
Something like C# partial class maybe. Define all of them in
sealed class
but implement them in separate file.
s

stantronic

11/27/2023, 11:28 AM
I would like to see a broader concept of extension classes - so you could define any class as
class Parent.Child()
3 Views