Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala工作表抛出错误_Scala_Intellij Idea - Fatal编程技术网

Scala工作表抛出错误

Scala工作表抛出错误,scala,intellij-idea,Scala,Intellij Idea,在IntelliJ(使用Scala 2.11.8)上运行Scala代码时出错: 我的Scala工作表有: import week4._ object nth { def nth[T](n: T, l: List[T]): T = { if (l.isEmpty) throw new IndexOutOfBoundsException else if (n==0) l.head else nth(n-1, l.tail) } val l1 = new Con

在IntelliJ(使用Scala 2.11.8)上运行Scala代码时出错:

我的Scala工作表有:

import week4._

object nth {
  def nth[T](n: T, l: List[T]): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth(n-1, l.tail)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth(2, l1)
}
错误:

错误:(9,20)未找到:类型Cons lazy val l1=新Cons(1,新Cons(2,新Cons(2,新Nil))) ^

错误:(6,16)值-不是类型参数T的成员 第n(n-1,左尾)
^您的
n
通过
T
参数化。在它内部,您使用
n(n-1,…)
递归调用它

n-1
的类型是什么
n
的类型为
T
1
的类型为
Int
无法推断结果类型为
T
类型,因此失败

我建议传递一个额外的参数,也许:

object nth {
  def nth[T](n: T, l: List[T], dec: T => T): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth[T](dec(n), l.tail, dec)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth[Int](2, l1, _ - 1)
}
编辑 将我的代码版本放在一个类中,该类扩展了应用程序。我已经放弃使用工作表了。太不可靠或隐藏的秘密太多

第二辑 右键单击工作表,按下
Recompile.sc
Run
.sc`,它就工作了。。。哦,工作表


即使将
T
更改为
Int
,也会有一个红色的
-
符号。。这应该是另一个问题,你是对的。需要显式参数化:)您必须首先编译week4包,然后尝试运行工作表。至少它对我来说没有任何代码变化
object nth {
  def nth[T](n: T, l: List[T], dec: T => T): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth[T](dec(n), l.tail, dec)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth[Int](2, l1, _ - 1)
}