Hacker News new | ask | show | jobs
by t0mek 924 days ago
This is similar to Kotlin single-expression functions, which are actually pretty useful:

    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()...`

4 comments

I don't really understand what makes that better than something like (from e.g. Swift):

    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).
There's no single line constraint in Ruby, either, as the article mentions; its a single expression, as in Kotlin, not a single line.
Yeah, I'm a fan of this.

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?

One of my least favourite Kotlin features. Breaks the uniformity of method declarations for minuscule gains, making it harder to visually parse a class body quickly.