为什么类型推断失败?
scala> val xs = List(1, 2, 3, 3)
xs: List[Int] = List(1, 2, 3, 3)
scala> xs.toSet map(_*2)
<console>:9: error: missing parameter type for expanded function ((x$1) => x$1.$times(2))
xs.toSet map(_*2)
Run Code Online (Sandbox Code Playgroud)
但是,如果xs.toSet已分配,则编译.
scala> xs.toSet
res42: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> res42 map (_*2)
res43: scala.collection.immutable.Set[Int] = Set(2, 4, 6)
Run Code Online (Sandbox Code Playgroud)
此外,走另一条路,转换为Set从List,并映射List规定.
scala> Set(5, 6, 7)
res44: scala.collection.immutable.Set[Int] = Set(5, 6, 7)
scala> res44.toList map(_*2)
res45: List[Int] = List(10, 12, 14)
Run Code Online (Sandbox Code Playgroud) 这种情况有效:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))
Run Code Online (Sandbox Code Playgroud)
然而,这不是:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))
Run Code Online (Sandbox Code Playgroud)
编译以此错误结束:
error: missing parameter type for expanded function ((x$4) => x$4.toString)
Run Code Online (Sandbox Code Playgroud)
现在,如果我这样写它再次编译:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (s => throw new Exception(s.toString))
Run Code Online (Sandbox Code Playgroud)
我相信有合理的解释;)