开发者

How to restrict a anonymous function's boundary?

开发者 https://www.devze.com 2023-01-19 11:49 出处:网络
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 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开发者_如何学Python 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?"


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))


I find a answer by Daniel, Anonymous functions and Maps in Scala , this answer let me clear how the parser process placeholder in this case. thanks for all.


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.



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

0

精彩评论

暂无评论...
验证码 换一张
取 消