I am trying to use placeholder syntax for simple map:
Array(1,2,3).map(if(_ % 2 == 0) _ * 2)
I was expecting to have the same effect as:
Array(1,2,3).map(i=>if (i%2==0) i * 2)
It complains
error: type mismatch;
found : Unit
required: Int => ?
I also tried:
Array(1,2,3).map(if(_ % 2 == 0) _ * 2 else _) //with else
Array(1,2,3).map(if((_:Int) % 2 == 0) (_:Int) * 2 else (_:Int)) //All typed
Array(1,2,3).map(if((_:Int) % 2 == 0) 0 else 1) //Typed and specific return Int
Every one of them gives error. How to properly use this syntax in this case?
Edit
The link states that filter(_:Boolean)
and filter (_ == true)
should work, but my trials with specific typing does not work. This link also states that if (_) x else y
should work, but in my case it does not. Need more explanation.
Edit 2
Tried:
Array(true,false).map(if(_) 0 else 1)
It works. But my case:
Array(1,2,3).map(if((_) % 2 == 0) 0 else 1)
Does not work.
Does this syntax only support such simple expressions?