【发布时间】:2014-12-13 20:34:39
【问题描述】:
我很难理解何时可以或不能省略括号和/或句号,以及这与 _ 的相互作用。
我遇到的具体情况是
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>))))
现在,我经常玩“切换符号直到它编译”,我认为这是一种次优的编程策略。这一切是如何运作的?
【问题讨论】:
-
还没有,谢谢。看着。
-
这应该有助于解决在哪里省略括号/点的问题:stackoverflow.com/questions/1181533/…
标签: scala type-inference higher-order-functions syntactic-sugar