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

使用多个泛型的Scala类型不匹配,scala,generics,constructor,Scala,Generics,Constructor,我正试图使用Scala为我的lambda微积分类原型化lazy无尽列表的功能。公共构造函数接受两个参数,应该创建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

我正试图使用Scala为我的lambda微积分类原型化lazy无尽列表的功能。公共构造函数接受两个参数,应该创建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)
                                                            ^

我到底做错了什么?

类中的参数化签名没有任何关于类型
B
与类型
A
之间关系的信息,因此编译器通常认为
懒散列表
主体
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) 
}

类中的参数化签名没有关于类型
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) 
}