Here are a few of my favourite shortcuts to work with Kotlin. If you have others, don't hesitate to mention them.
1. chunked doc
Works on Iterables that are most common to us, like List
s or Sequence
s.
It does exactly what it sounds like, splits a collection in equal parts (if possible) and enables us to transform each resulting sublist, all in the same operation.
val initialList = listOf("chair", "table", "couch")
val chunkedTwo = initialList.chunked(2)
// chunkedTwo -> [["chair", "table"], ["couch"]]
val transform = initialList.chunked(2) { subList -> subList.last() }
// transform -> ["table", "couch"]
You may have needed this or not, but it's nice to know it's there. Sometimes when you think about it, it's not that difficult to do, but reimplementing the same things may cause you to slip up somewhere, somehow.
2. with doc
Scoped functions like with
enable us to write more verbose code. This one can cut down on the length of the line by scoping to a nested variable in your object. But I think an example is most fit here.
data class Birthday(val year: Int, val month: Int, val day: Int)
data class Person(val name: String, val birthday: BirthDay)
data class Employee(val position: String, val person: Person)
// having a method that receives an employee and computes a string
fun nameAndBirth(employee: Employee) = with(employee.person.birthday) {
// in here, the scope is actually Birthday
"${employee.person.name}: $day/$month/$year"
}
}
Another cool fact about with
is that, like the other functions run
, let
and so on, it will return the last value that was computed. In our case, the String
that contains the name and birth of the employee.
3. associateBy doc
This is a great shortcut to create maps for objects that you need to find later on, by certain keys (id, name, length and so on). You could find it really useful, since this, in many cases is repeatable.
data class Room(val id: Long, val name: String, val area: Double)
val rooms = listOf(Room(1, "living", 40.5), Room(2, "living", 39.3))
val associated = rooms.associateBy { it.name }
// associated -> { "living"=Room(2, "living", 39.3)}
val associated2 = rooms.associateBy { it.id }
// associated2 -> { 1=Room(1, "living", 40.5), 2=Room(2, "living", 39.3)}
Be careful since if two keys match, only the last one will be present in the resulted map.
Hope you can try these out if you didn't already.
Thanks for Reading
Top comments (0)