我很難理解何時可以或不能省略方括號和/或句點,以及如何這與_相互作用。命名參數vs _,點符號與中綴操作,在Scala中使用高級函數時的捲曲與圓括號
我不得不這樣做的特例是
val x: X = ???
val xss: List[List[X]] = ???
xss map x :: _ //this doesn't compile
xss map _.::(x) //this is the same as the above (and thus doesn't compile)
上述兩個似乎是相同的xss.map(_).::(x)
xss map (x :: _) //this works as expected
xss map {x :: _} //this does the same thing as the above
同時,下面還失敗:
xss.map xs => x :: xs //';' expected but '=>' found.
xss.map x :: _ //missing arguments for method map in class List; follow this method with `_' if you want to treat it as a partially applied function
//so when I try following the method with _, I get my favourite:
xss.map _ x :: _ //Cannot construct a collection of type That with elements of type B based on a collection of type List[List[Main.X]]
//as opposed to
xss map _ x :: _ //missing parameter type for expanded function ((x$1) => xss.map(x$1).x(($colon$colon: (() => <empty>))))
權現在,我經常玩「切換符號,直到它編譯」我認爲是次優編程策略。這一切如何工作?
您是否看到http://stackoverflow.com/questions/2173373/scala-foreach-strange-behaviour? – sschaef 2014-10-18 11:15:12
還沒有,謝謝。看着。 – Martijn 2014-10-18 11:18:45
這應該有助於解決掉圓括號/圓點的問題:http://stackoverflow.com/questions/1181533/what-are-the-precise-rules-for-when-you-can-omit-parenthesis-點 - 大括號 - f – sschaef 2014-10-18 11:23:30