7 Dec 2011

Abusing Scala’s anonymous argument

In Scala, you can use the underscore (_) to refer to an argument you are lazy to name.

val numbers = List(1,2,3,4)
numbers.map(2 * _)  // List(2, 4, 6, 8)

You can go a step further.

val numbers = List(1,2,3,4)

You can completely omit the _ as well, because * is actually a method on 2. Scala is smart enough to understand that it requires one parameter, and automatically passes it each element of the list.

In my last post on Scala, I mentioned how Scala’s power can be easily abused. This is one instance where it’s easy to end up abusing the convenience offered by the language. Let’s look at another code snippet:

// constant defined somewhere
val photoPath = "photos/"
// in another file
val memberIds = List("abc","def","ghi","jkl")
val photoUrls = memberIds.map("http://example.com/member/"+photoPath+)

See that innocuous looking + operator at the end of the last line? It’s very easy for someone who is tired at the end of a long day to just delete that, thinking that it’s a stray operator left behind by some lazy developer. Ouch.

Having said that, the use of anonymous arguments is elegant in some cases. Consider this:

def complicatedLogic(x:Int) = {
  // do something complicated
val input = List(1,2,3,4)
val output = input.map(x => complicatedLogic(x))

We can rewrite that last line this way:

val output = input.map(complicatedLogic)

P.S: I have taken the liberty to use the term “anonymous argument” here to refer to this handy trick – but I will update the post if someone can tell me what this behavior is referred actually as.

You can follow me on Twitter right here.

Tagged with:

Leave a Reply