为什么类型推断失败?
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) 以下是我的错误:
trait Foo[A]
class Bar[A](set: Set[Foo[A]] = Set.empty)
Run Code Online (Sandbox Code Playgroud)
这产生了
<console>:8: error: polymorphic expression cannot be instantiated to expected type;
found : [A]scala.collection.immutable.Set[A]
required: Set[Foo[?]]
class Bar[A](set: Set[Foo[A]] = Set.empty)
^
Run Code Online (Sandbox Code Playgroud)
我必须重复类型参数,这非常烦人Set.empty.为什么类型推断失败了这个默认参数?以下作品:
class Bar[A](set: Set[Foo[A]] = { Set.empty: Set[Foo[A]] })
Run Code Online (Sandbox Code Playgroud)
请注意,这与此无关Set:
case class Hallo[A]()
class Bar[A](hallo: Hallo[A] = Hallo.apply) // nope
Run Code Online (Sandbox Code Playgroud)
奇怪的是,这不仅有效:
class Bar[A](hallo: Hallo[A] = Hallo.apply[A])
Run Code Online (Sandbox Code Playgroud)
......还有这个:
class Bar[A](hallo: Hallo[A] = Hallo()) // ???
Run Code Online (Sandbox Code Playgroud)