list - Scala 列表错误

标签 list scala typing

在学习了大量 Java 和一些 Haskell 之后,我想看看 Scala。从下面的代码中,我收到此错误消息
type mismatch; found : List[Nothing] => Option[Nothing] required: List[Int] => Option[Nothing]
我不知道我做错了什么:

object MyFirstScalaObject {

  def main(args: Array[String]) {
      lazy val testValues:List[List[Int]] = List((1 to 10).toList, null, List());

      println(  testFunction(last, testValues));
  }

  def testFunction[I, O](f : I => O, inputs : List[I]):
      List[(I, O)] = 
    inputs.zip(inputs.map(f));

  def last[A](xs:List[A]):Option[A] = xs match {
    case x::Nil => Some(x);
    case _::xs => last(xs);
    case _ => None;
  }

}

感谢您的任何建议。

干杯,

最佳答案

由于scala中类型推断的工作方式,无法确定last的类型参数是什么。必须是,所以它必须采取过于保守的后备猜测它是 Nothing .

您可以在调用 testFunction 时明确指定类型:

testFunction[List[Int],Option[Int](last, testValues)

或者您可以更完整地记录 testFunction 中类型参数之间的关系。声明,它将为类型推断器提供更多信息:
def testFunction[A, I[_], O[_]](f : I[A] => O[A], inputs : List[I[A]]): List[(I[A], O[A])]

这明确说明 I 和 O 是类型构造函数(kind * -> *),现在 f 的输入/输出类型更加具体,推理器可以正确推断最后一个函数的 A 参数必须是 Int。

关于list - Scala 列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13885272/

相关文章:

python - 组合字符串列表,提高性能

scala - 为什么我需要jsr305才能在scala中使用guava?

scala - 在Scala中将方法提取到独立函数

scala - 无法读取spark scala中的conf文件

objective-c - 动态类型、Objective-C,它是如何工作的?

abap - 使用 ANY 或 DATA 键入字段符号

lua - Lua 中记录类型的约定是什么?

Spring Autowiring 列表

python - 在列表理解中重用修改后的键

python - 在 python 中,为什么列表与列表不同[ :]?