I have a `sealed interface Foo { /* ... */ }` and ...
# getting-started
y
I have a
sealed interface Foo { /* ... */ }
and a bunch of existing classes that implement it, and now years later I want to add an
interface Bar : Foo { fun bar() = someDefaultImpl() }
. from my understanding, I would have to "pollute" the existing code, by doing one of: 1. changing every single existing
Foo
-implementer from
MyClass : Foo
to
MyClass : Foo, Bar
, and also implement
fun bar()
in the definition of
MyClass
2. modifying
sealed interface Foo
by adding
fun bar()
to
Foo
(and then delete
interface Bar
), and again implement
fun bar()
in the definition of whatever originally implemented
Foo
instead, is there a way to "auto-implement"
Bar
for everything that implements
Foo
, like Rust's blanket implementations? so that all of this logic live in a different file and can be deleted whenever I want without any code changes as described above? in other words, I want to emulate Rust traits, in that the logic of the interface can live far away from the implementer of the interface
huh. looks like there are some cursed-looking stuff you can do with extensions here. let's see if I can get this working.
not even cursed. simply using the fact that
Foo
is
sealed
(which I could already guess would came in handy) to write something like,
fun Foo.bar() = when (this) { /* ... */ }
which is even statically resolved, as Kotlin docs explain
what's more, an
else
branch gives you a default impl.
pretty cool. good job kotlin
well... first caveat I've encountered is visibility
p
What if make Foo extends Bar?
y
@PHondogo hey, can you explain?
p
interface Foo : Bar
y
isn't that what I wrote above?
or are you saying I should flip the inheritance?
1
p
Yes
If possible for your business logic
c
Yep, by flipping the inheritance you can use regular methods in the Bar interface, which will be used as a default implementation for all other existing classes
y
@PHondogo @CLOVIS coming back to this again, I now see what you mean. I can define the entire impl in the file where I declare
Bar
, and as far as I can see the only change needed outside of this file is to change
sealed interface Foo
to
sealed interface Foo : Bar
. wonderful.
TIL. thanks.