使用多个泛型的Scala类型不匹配

时间:2016-05-28 15:11:03

标签: scala generics constructor

我正在尝试使用Scala为我的lambda演算类原型化懒惰无限列表的功能。公共构造函数有两个参数,应该创建LazyList [A,A]。

class LazyList[A,B] private (private val first: A, private val mapper: A => B, private val successor: A => A) {
  def this(first: A, successor: A => A) = this(first, (e: A) => e, successor)

  def head: B = mapper(first)

  def tail(): LazyList[A,B] = new LazyList(successor(first), mapper, successor)
  def map[R](func: B => R) = new LazyList[A, R](first, func.compose(mapper), successor)
  def at(index: Long): B = if (index == 0L) head else tail().at(index - 1)
  def sublist(end: Long): List[B] = if (end == 0L) List(head) else head :: tail().sublist(end - 1)

  override def toString = s"LazyList($first, $mapper, $successor)"
}

但代码编译失败并出错。

Error:(20, 65) type mismatch;
 found   : e.type (with underlying type A)
 required: B
  def this(first: A, successor: A => A) = this(first, (e: A) => e, successor)
                                                            ^

我究竟做错了什么?

1 个答案:

答案 0 :(得分:2)

类中的参数化签名没有关于类型B与类型A的关系的任何信息,因此编译器通常认为LazyList体内的任何地方都是B不是A,这就是当您尝试将A => A分配给A => B时,编译器会抱怨的原因。

您应该创建一个不是this()的替代构造函数,而是创建伴随对象中的工厂方法。请注意,此用法的A是一个参数,与LazyList的正文中的A无任何关联:

object LazyList {
  def apply[A](first: A, successor: A => A): LazyList[A, A] = new LazyList(first, identity, successor) 
}
相关问题