views:

168

answers:

4

I saw a below code:

Map(1 -> "one", 2 -> "two") map _._1

this return a Iterable[Int], but if I want to do nothing with map, how to do it?

I want to do something like below, but the below code can't compile, I know because it a object instance not a function, but how to create a function to do x => x and use placeholder:

Map(1 -> "one") map (_)  // map (Int, String) to (Int, String) by nothing change
// I test some other way, but all can't compile

how to do this?

UPDATED

Sorry for confuse passionate person. I want to know why map (_) != map (x => x), compiler transform this code to (x$1) => Map(1.$minus$greater("one")).map(x$1) why not Map('a'.$minus$greater(1)).map((x$1) => x$1), and does there has a way can use _ make this code?

I used below code to help compiler inferred the _ type:

Map(1 -> "one") map (_:((Int, String))=>(Int, String))
// but it return (((Int, String)) => (Int, String)) => scala.collection.immutable.Map[Int,String] = <function1>

It seem the parser was not sure where to put the beginning of the anonymous function. So my new question is "How to help the parser to restrict a anonymous function's boundary?"

A: 

Hi!


  Map(1 -> "one") map((x)=>x)

walla
sorry, I know that can do, but I want to use placeholder syntax to do this.
Googol Shan
+2  A: 

Not sure I understand the question, but identity is maybe what you're looking for:

scala> Map(1 -> "one") map (identity)
res66: scala.collection.mutable.Map[Int,java.lang.String] = Map((1,one))

or, do some tricks:

scala> def __[A](x: A): A = x
__: [A](x: A)A

scala> Map(1 -> "one") map (__)
res1: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one))
IttayD
:-) just think about such function
walla
yes, this is what my wanted. Use scala inner method to do this. but does there has some other way that use placeholder to deal this? This question just from my crazy idea that want to know why `_ != x => x`, why _ can't be representative of a function like `Predef.identity` does. It's not a really question.
Googol Shan
+1  A: 

I can't see any value in what you're trying to do here, the correct way to map a collection to itself is not to call map!

Wrong:

Map(1 -> "one") map (_)

Right:

Map(1 -> "one")

It isn't even useful as a shallow copy operation, the default Scala Map is immutable and there's no point in copying it.

Kevin Wright
sorry for confuse you, like my above comment, this just a question in my head, not a really question.
Googol Shan
+2  A: 

I find a answer by Daniel, http://stackoverflow.com/questions/3505125/anonymous-functions-and-maps-in-scala/3507163#3507163 , this answer let me clear how the parser process placeholder in this case. thanks for all.

Googol Shan