Everything else is just a tool to model your domain in a way that’s easier to read and reason about, and to produce much shorter code. Interfaces define module boundaries and can be mocked to enable simpler testing. Through classes, objects, and data structures, you can model your domain entities. Enums make a list of limited options crystal clear. Extensions allow you to add functionality to existing types, without having access to their original source code, giving advantage of better logic structure. With generics, you can write universal code, promoting reuse. And overloaded operators give that extra edge to common operations that benefit from succinct, crisp syntax.
Generics
Generics let you write more general code that is not tied to specific types and is much more reusable, avoiding copy-pasting in many situations. If you have code that is applicable to more than one data type, you can make that type into a generic parameter and use it to write your logic.
Generics
Interfaces and classes can have generic parameters:
interface Producer<T> {
fun nextValue(): T
fun hasNext(): Boolean
}
class Stack<T>(initialValues: List<T>): Producer<T> {
private val values = initialValues.toMutableList()
fun push(value: T) {
values.add(value)
}
fun pop(): T? = values.removeLastOrNull()
override fun nextValue(): T = values.removeLast()
override fun hasNext(): Boolean = values.isNotEmpty()
}
Functions can have generic parameters, too:
fun <T> makeProducer(vararg values: T): Producer<T> = Stack(values.toList())
val producer = makeProducer(1, 2, 3)
val confusedProducer = makeProducer<Any>(1, true, "text")