y
04/06/2025, 1:37 PMsealed 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 interfacey
04/06/2025, 2:07 PMy
04/06/2025, 2:10 PMFoo
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 explainy
04/06/2025, 2:11 PMelse
branch gives you a default impl.y
04/06/2025, 2:15 PMy
04/06/2025, 2:17 PMPHondogo
04/07/2025, 2:34 PMy
04/07/2025, 2:37 PMPHondogo
04/07/2025, 2:40 PMy
04/07/2025, 2:41 PMy
04/07/2025, 2:41 PMPHondogo
04/07/2025, 2:42 PMPHondogo
04/07/2025, 2:43 PMCLOVIS
04/09/2025, 8:09 AMy
04/09/2025, 9:23 AMBar
, 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.y
04/09/2025, 9:23 AM