"return" vs expression body

#1

Functions with only a single expression can be written with = instead of return. In the end it is a matter of taste, but I’m interested how you handle it. Do you follow a general rule in your coding conventions? The official style guide recommend to use expression body syntax whenever possible.

I see the following possibilities:

  • Never using expression body (=)
  • Using expression body whenever possible
  • Using expression body only for short expressions (one-liner)

Examples

Java-style return:

override fun findByPlant(plantId: PlantId): List<Vehicle> {
    return entityManager.createNamedQuery(Vehicle.Queries.findByPlant, Vehicle::class.java)
        .setParameter("plantId", plantId)
        .resultList
}

Expression body:

override fun findByPlant(plantId: PlantId): List<Vehicle> =
    entityManager.createNamedQuery(Vehicle.Queries.findByPlant, Vehicle::class.java)
        .setParameter("plantId", plantId)
        .resultList
#2

I’m using it whenever possible. I don’t specifically refactor code to achieve that goal, but if my function’s body is just one expression, I’m using this syntax, why waste tokens for unnecessary return, I don’t think it’ll add any clarity. On the other hand if that one expression could be better expressed as a multiple statements, I’ll use return, no problems with that. Basically it’s the same as with Java lambda expressions, the difference is that Kotlin allows more code to be expressed with a single expression.

#3

I would use = when the expression fits into a single line. I think that was also the intention of this = thing by the Scala people.

#4

I use expression body style for multi-line expressions also, but only if the expression is terminated with a closing brace.

Example:

fun String.truncate(max: Int) = when {
   length <= max -> this
   else -> this.substring(max)
}
2 Likes
#5

I usually use body expression when possible.

#6

I use it for “multiline” blocks as well. Basically where there is an inline function that effectively functions like a function body specialiser (whether it is when, use or something else). In such case it looks just cleaner than putting it in a function body.

1 Like