To Top
# Kotlin ## Useful things - Instead of having a precondition for a function in an if, you can do `require(some_precondition, lambda_to_trigger_if_requirement_not_met)` - You can add an element to an immutable list (returning a new list with that at the end) by doing `listA.plus(elem)` - `hashCode` is used for sorting stuff in an unordered container into buckets, and then `equals` would be used in the comparisons within the buckets, so you need to make sure `equals` is consistent with `hashCode` (in IntelliJ you can automatically generate them both) - Generally try to use immutable properties for `hashCode`/`equals` - A concise way of getting reasonable `equals`/`toString`/`hashCode` (and some others too) implementations is to use `data class`es instead of just `class`es
```kt data class box(val width: Int, val height: Int) val boxA = box(2, 3) val (a, b) = Pair("thirty two", 2.7) // a = "thirty two" // b = 2.7 val (c, d) = boxA // c = 2 // d = 3 ``` ```kt val x: Int? = something?.length // Instead of if(x != null) { println("Line length: " + x*3) } // you could do x?.let { len -> println("Line length: " x*3) } ``` Templated stuff exists too: ```kt class something
{ fun
map(f: (T) -> U): List
{ // ... } override fun toString(): String { // ... } fun add(elem: T) { // ... } } // i.e, could be a container of elements which are of type T // and the map function maps from those to elements of type U val containerA = something
() containerA.add(12) containerA.add(15) println(containerA.map({ el -> el*3 }) // [36, 45] for example ```