【发布时间】:2017-07-21 00:09:37
【问题描述】:
我刚刚开始学习 scala。我正在尝试编写一个函数来反转任意类型的列表。
下面是代码:
def reverse [A] (l:List[A]):List[A] = {
val size:Int = lenList(l) // i have implemented this func separately
if (l.isEmpty) List()
else {
var newList = List()
for (i <- 1 to size)
{
var temp = l(size - i)
newList = newList :+ temp //type mismatch error here
}
newList
}
}'
这是上面代码编译时的错误:
当我将newList 声明更改为var newList = List[A]()(与作为参数传递的List 相同的类型)时,代码编译成功。
我的问题是:
当
newList的类型为List[Nothing]而temp是type A的元素时,为什么行newList = newList :+ temp上会出现类型不匹配?为什么编译器在语句中没有
List[A]类型时会说Found:List[A]?谁能告诉我这个特定类型不匹配错误发生的原因?
另外我想知道为什么我更改声明时编译的代码是什么原因?
我的声明对最初引发错误的语句有什么影响?
我相信在这种情况下下面的错误消息是合理的
found:List[Nothing]
Required:List[A]
而不是我遇到的:
found:List[A]
Required:List[Nothing]
由于声明中使用了List[Nothing] 类型的newList,并且我尝试附加的元素是type A,因此可以理解所需的类型应该是List[A]。
【问题讨论】:
-
调用
List()对应于工厂List.apply[T],其中T被推断为Nothing,因为您没有指定它,在val声明中也没有指定显式类型或在工厂电话上。val newList: List[A] = List()或val newList = List.empty[A]