相关疑难解决方法(0)

使用.toSet设置的类型推断失败?

为什么类型推断失败?

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)

此外,走另一条路,转换为SetList,并映射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)

scala type-inference

26
推荐指数
3
解决办法
1725
查看次数

在Scala中,为什么我会将这个"多态表达式无法实例化为预期类型"?

为什么在Scala 2.9.0.1中会出现以下情况?

scala> def f(xs: Seq[Either[Int,String]]) = 0
f: (xs: Seq[Either[Int,String]])Int

scala> val xs = List(Left(0), Right("a")).iterator.toArray
xs: Array[Product with Serializable with Either[Int,java.lang.String]] = Array(Left(0), Right(a))

scala> f(xs)
res39: Int = 0

scala> f(List(Left(0), Right("a")).iterator.toArray)
<console>:9: error: polymorphic expression cannot be instantiated to expected type;
 found   : [B >: Product with Serializable with Either[Int,java.lang.String]]Array[B]
 required: Seq[Either[Int,String]]
       f(List(Left(0), Right("a")).iterator.toArray)
                                            ^
Run Code Online (Sandbox Code Playgroud)

更新:Debilski提出了一个更好的例子(不是100%肯定这表明了相同的潜在现象):

Seq(0).toArray : Seq[Int] // compiles
Seq(Some(0)).toArray : Seq[Option[Int]] // doesn't
Run Code Online (Sandbox Code Playgroud)

scala

22
推荐指数
2
解决办法
1万
查看次数

标签 统计

scala ×2

type-inference ×1