by t0mek · 2y ago · 0 comments
fun double(x: Int) = x * 2
https://kotlinlang.org/docs/functions.html#single-expression...However, in Kotlin there's no single-line constraint, so it's possible to define an expression function e.g. with a long chain of collection methods: `filter().map().findFirst()...`
func double(x: Int) -> Int { x * 2 }
It just seems less readable because it's introducing not only an additional syntax for declaring functions, but also a secondary meaning for the "=" operator.edit: in my original version of this comment I forgot to add the return type syntax, "-> Int", which Swift needs. I suppose eliding the return type is a bit more terse. You could also assign a closure in Swift to avoid that, like:
let double = { (x: Int) in x * 2 }
which is about as short as the Kotlin version, and has the advantage of not being "special" in any sense from any other Swift syntax (i.e., it's just assigning a standard closure to a variable).Was a bit of fun in scala to see if you could rewrite something to be a single statement.
Sometimes the single statement version wasn't clearer, but sometimes it really was.
Point free programming takes this to code golf type territory and can be fun as a puzzle if not for real world code.
Maybe ruby just doesn't do it well?