【发布时间】:2018-11-04 20:05:25
【问题描述】:
def linearInterpolation(weights: Seq[Double], points: Seq[Seq[Double]]) : Seq[T] = {
weights.zip(points).map(
weight_point => weight_point._2.map(coordinate => weight_point._1 * coordinate)
).reduce((point_a : Seq[Double], point_b : Seq[Double]) => point_a.zip(point_b).map(coordinate_points => (coordinate_points._1 + coordinate_points._2).asInstanceOf[T]))
}
在这段代码中,我试图将返回的类型 Seq[Double] 转换为 Seq[T]。在执行调用时,T 可以是例如Double 或 Int。
这个转换应该是感谢.asInstanceOf[T]实现的。
错误
代码编译。
但如果我执行它,我会收到以下错误:
错误:(25, 61) 类型不匹配; 发现:(Seq[Double], Seq[Double]) => Seq[T] 必需: (Seq[Any], Seq[Any]) => Seq[Any] ).reduce((point_a : Seq[Double], point_b : Seq[Double]) => point_a.zip(point_b).map(coordinate_points => (coordinate_points._1 + coordinate_points._2).asInstanceOf[T]))
错误:(25, 13) 类型不匹配; 发现:序列[任何] 必需:序列[T] ).reduce((point_a : Seq[Double], point_b : Seq[Double]) => point_a.zip(point_b).map(coordinate_points => (coordinate_points._1 + coordinate_points._2).asInstanceOf[T]))
问题
为什么执行失败?如何实现从Seq[Double] 到Seq[T] 的这种转换?
【问题讨论】:
标签: scala generics type-conversion generic-programming generic-collections