I have a `sealed class` with a ton of stuff. I nee...
# getting-started
y
I have a
sealed class
with a ton of stuff. I need to name it from outside (maybe an ill-advised API decision, let's pretend otherwise for now) however just about everything else (constructors, companion object methods, etc.) should be
internal
. is there a trick to reducing the number of times I use the word
internal
in my source code? for example,
internal companion object
was useful here.
j
Maybe you could use a sealed interface, with only the public stuff, and then implement it with an internal class?
1
thank you color 1
y
You could have its only direct subclass be an internal sealed class.
thank you color 1
y
both of these are good suggestions for me, especially the one from @Joffrey I use the sealed class as a namespace, but using a sealed class that implements an interface, or having a subclass as "the namespace" and importing it when I need the namespacing, would work well.
j
If you just use the sealed class as a namespace, then why not make it an interface? (instead of making it implement an interface?)
y
I'm probably misunderstanding you, but I currently have
Copy code
sealed class Foo {
  internal class Bar1 : Foo()
  internal class Bar2 : Foo()
}
class ThisThingIsPublic(foo: Foo)
and I would like to avoid having to write
internal
everywhere. so my understanding of your suggestion was making
Foo
internal and then adding a public
FooInterface
j
Yes, sorry if I was unclear. I did mean to use a separate public interface to clearly define the public-facing stuff, and then use whatever internal container to implement it and get all inside declarations
internal
by default. I was just puzzled by the "namespace" aspect. If
Foo
doesn't have any state and is just for namespace, then it could itself be an interface (independently of the idea of splitting the public interface).
y
ah, I see. so then you'd import the internal class that is inside the public interface
Foo
? anyway, I understand. thanks.
j
Yeah everything would just be the same as with the
sealed class
. It's really just nitpicking on a detail here. I always suggest to replace
sealed class
with
sealed interface
if we're not using state (or other class-only capabilities), just like I would suggest using
val
instead of
var
if we're not reassigning the variable.
💯 2