Pergunta

This question is not about the recommended practices for notation in method chaining, its about understanding this particular case.

I am learning Scala and Play for about 2 weeks now. I have prior one month learning experience in scala sometime in 2011.

I am having trouble understanding why this line is not working

    List(1,2,3) map {x=>x*2}.filter((x:Int)=>x==2)

But this one is working

    List(1,2,3).map{x=>x*2}.filter((x:Int)=>x==2)

One reason that I can think of is that the filter is being called upon the function value rather than the resulting collection.

Why is it still not working when Space and Dot notation are mixed? If I keep pure Space or Dot notation then it works otherwise not.

I would have not got confused if I only saw pure notation everywhere. I have seen mixed notation especially in the Play codebase. What am I missing?

Foi útil?

Solução

It works as expected.

This line:

List(1,2,3) map {x=>x*2}.filter((x:Int)=>x==2)

means

List(1,2,3) map ( {x=>x*2}.filter((x:Int)=>x==2) )

It is definitely a error, but you could use it like this:

val f1 = (x: Int) => x * 2
val f2 = (x: Int) => x + 2

List(1,2,3) map f1.andThen(f2) // List(1,2,3).map( f1.andThen(f2) )
//List[Int] = List(4, 6, 8)

This code creates new function as composition of 2 functions: {(x: Int)=>x*2}.andThen((x:Int)=> x + 2) and then applies map method to it.

You could mix Space or Dot notations, but you should know that "priority" of dot is higher.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top