Scala map() vs map{}

I was wondering the other day what the difference really was, in Scala, between

1 val list = List(1, 2, 3, 4)
2 list.map(x => x * x)

and

1 val list = List(1, 2, 3, 4)
2 list.map { x => x * x }

So, I figured I’d take a look at the map function defined on the List class. I winded up finding the definition in the TraversableLike trait as follows:

 1 def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
 2   def builder = { // extracted to keep method size under 35 bytes, so that it can be JIT-inlined
 3     val b = bf(repr)
 4     b.sizeHint(this)
 5     b
 6   }
 7   val b = builder
 8   for (x <- this) b += f(x)
 9   b.result
10 }

Let’s ignore the builder for now since it’s the less important part of this question. We’re interested in the first set of parameters, f: A => B. This seems to be a normal argument yet we can apply it in two different ways. That got me thinking a little bit and so I decided to play around a bit to see if I can figure this out anecdotally, before looking up the proper literature.

Non-Function Arguments

I first wanted to try with some simple functions that didn’t have functions as arguments to see if this format is generally applicable. I came up with some simple tests.

 1 def echo(x: String) = println(x)
 2  
 3 echo{"hello"}    // valid
 4 echo("hello")    // valid
 5  
 6  
 7 def echoName(name: String, x: String) = println("$name: $x")
 8  
 9 echoName{"John", "hello"}        // invalid
10 echoName("John", "hello")        // valid
11 echoName({"John"}, {"hello"})    // valid

So from this it seems to indicate that braces are not interchangeable with parenthesis. However, it does seem that "John" and {"John"} are interchangeable. In fact, if we look at the REPL we see:

1 val s1 = {"hello"}     // s1: String = hello
2 val s = "hello"        // s: String = hello

This may not be a surprise to some, but that means that something like echo {"hello"}can really just be thought of as a shorthand for echo({"hello"}). But what about {x => x * x}. We can assume that just returns a function, correct? So that would means we can assume that these are functionally equivalent:

1 val list = List(1, 2, 3, 4)
2 list.map(x => x * x)
3 list.map({x => x * x})

And, anecdotally, this seems to be true.

Back to Functions

So based on our findings, what is the point of the curly braces and when would they be useful. Let’s do some experiments with a little more meat and see if we can find an answer. First let’s try a slightly larger map example.

 1 val list = List(1, 2, 3, 4)
 2  
 3 // not valid (compile-error)
 4 list.map(x =>
 5   val y = x * x
 6   val z = y * x
 7   Math.sin(z / x)
 8 )
 9  
10 // valid
11 list.map{x =>
12   val y = x * x
13   val z = y * x
14   Math.sin(z / x)
15 }

Ah ha, so there is a good reason to use curly braces. It looks like the parenthesis version cannot handle multiple statements and is only expecting a single expression. Furthermore, I found this bit interesting as well:

1 val f1 = (x : Int => x * x)    // invalid - compiler error (can't resolve x)
2 val f2 = (x : Int) => x * x    // valid
3 val f3 = {x : Int => x * x}    // valid

The same syntax using parenthesis cannot be used to define the function outside of the map unlike the version with curly-braces. Very interesting.

The Real Story

Okay, at this point I feel like I’ve made some interesting findings, but I’m curious what the Internet has to say about such things. So I figured I’d let her weigh in. I came across a few different posts:

Surprisingly, all three answers were by the same person. For someone strapped for time when it comes to blogging, he sure does seem to make a lot of appearances on this topic. ;-D

All in all, there seems to be quite a bit of discussion with some grey areas still that I still don’t fully understand. In those cases the compiler seems to be the specification, which is never preferable (IMO) for many reasons. Oh Scala, you are an interesting little language.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值