【发布时间】:2017-03-10 07:17:18
【问题描述】:
在这个参数化函数中,为什么我需要强制转换?我怎样才能摆脱它?
/** Filters `xs` to have only every nth element.
*/
def everyNth[A <% Iterable[B], B](xs: A, n: Int, offset: Int = 0): A =
(xs.zipWithIndex collect { case (x, i) if (i - offset) % n == 0 => x }).asInstanceOf[A]
如果最后没有演员表,我会收到以下错误消息:
type mismatch; found : Iterable[B] required: A
这个函数(带有强制转换)适用于我尝试过的所有情况,并且我通过在 REPL 中键入以下内容知道 Scala 能够在不在上下文中正确推断结果类型参数化函数:
scala> val a: Stream[Int] = (Stream.from(0).zipWithIndex collect { case (x, i) if (i + 3) % 5 == 0 => x })
a: Stream[Int] = Stream(2, ?)
scala> a take 10 force
res20: scala.collection.immutable.Stream[Int] = Stream(2, 7, 12, 17, 22, 27, 32, 37, 42, 47)
请解释一下!
【问题讨论】:
-
使用
CanBuildFrom解决问题的类似问题:Function which generically takes a type and returns the same type。我无法解决这个问题,其他人? -
我让 CanBuildFrom 来解决我的问题,并将解决方案放入答案中。如果您好奇,请参阅下面的答案。
-
不错的答案!顺便说一句,您可以接受自己的答案...
标签: scala