2 ms·
Kotlin has a few nice patterns here. It allows inheritance but only if you mark your class as open (it's closed by default). This prevents people inheriting fro
by jillesvangurp 3y ago
Kotlin has a few nice patterns here. It allows inheritance but only if you mark your class as open (it's closed by default). This prevents people inheriting from things that weren't designed from that. It also has extension functions, which allows you to add functions and properties to types without having to inherit from them. This is very nice for fixing things that come with Java libraries to be a bit more Kotlin friendly. Spring offers a lot of Kotlin extension functions for its Java internals out of the box. Another nice pattern is interface delegation where you can implement an interface and delegate to another object that implements that interface:
class Foo(private val myMap: Map<String,String>=mapOf()): Map<String,String> by myMap
This creates a Foo class that is a Map that delegates to the myMap property under the hood. So you side step a lot of the issues with inheritance; like exposing the internal state of myMap. But you can still override and extend the behavior. Replacing inheritance with delegation is built into the language.
The net result of this is that inheritance is rarely needed/used in Kotlin. It's there if you really need it but usually there are better ways.
Scala and other languages of course have similar/more powerful constructs. But Kotlin is a nice upgrade over Java's everything is non final by default (or generally defaulting to the wrong thing in almost any situation). Go has a nice pattern based on duck typing where instead of declaring interfaces, you can just treat something that implements all the right functions as if it implements a type. Rust similarly has some nice mechanisms here. All these are post-Java languages that de-emphasize inheritance.
- frizlab 3y agoSame with Swift
- pdpi 3y agoOne of the ways that I think Kotlin and Rust are objectively better than Java and C++ is in that they have saner defaults than their predecessors (like open/final and mut/const). I've lost count of how many talks I've watched by Kate Gregory where she advocates for people tagging everything they can as const in their C++, but asking people to eat their veggies never works.
- jonnycomputer 3y agoSane defaults are the bomb. Defused bomb.