Smart casts on polymorphic collections
Kotlin has a super concise and safe way to narrow down a polymorphic list to a specific sub-type using the as? syntax.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Animal { | |
val name: String | |
} | |
data class Monkey(override val name: String): Animal | |
data class Fish(override val name: String): Animal | |
val animals: List<Animal> = listOf(Monkey("gorilla"), Fish("trout"), Monkey("oranutan")) | |
val monkeys: List<Monkey> = animals.mapNotNull { it as? Monkey } |
Logging return values
There are situations, where we want to log the return value of a function before actually returning it. Usually, this is done by storing the return value into a variable, doing the log statement and finally returning that variable. Kotlin makes this is a bit simpler with the .also keyword for side-effects. Using .also, we don't have to introduce this artificial variable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Service(dependency: Dependency) { | |
private val logger = KotlinLogging.logger {} | |
fun doSomething(userId: String): Int { | |
return dependency.evaluate(userId = userId).also { result -> | |
logger.trace { "UserId '$userId' was evaluated to: $result" } | |
} | |
} | |
} |
... more to come