【问题标题】:Scala Worksheet throwing errorScala工作表抛出错误
【发布时间】:2017-08-15 14:18:31
【问题描述】:

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

package week4

/**
  * Created by BigB on 15/08/17.
  */
trait List[T] {
  def isEmpty: Boolean
  def head: T
  def tail: List[T]
}

class Cons[T](val head: T, val tail: List[T]) extends List[T] {
  override def isEmpty: Boolean = false
}

class Nil[T] extends List[T] {
  override def isEmpty: Boolean = true

  override def head: T = throw new NoSuchElementException("Nil.head")

  override def tail: List[T] =throw new NoSuchElementException("Nil.tail")
}

我的 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) not found: type Cons 惰性 val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil))) ^

错误:(6, 16) 值 - 不是类型参数 T 的成员 否则 nth(n-1, l.tail) ^

【问题讨论】:

  • 你必须先编译 week4 包,然后尝试运行工作表。至少它对我有用,无需任何代码更改

标签: scala intellij-idea


【解决方案1】:

您的nth 参数化为T。在里面你用nth(n-1, ...)递归调用它。

n-1 的类型是什么? nT 类型,1Int 类型,结果类型不能被推断为 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)
}

编辑

将我的代码版本放入extends App 可以按预期工作的类中。我已经放弃使用工作表了。太不可靠或隐藏的秘密太多。

编辑2号

右键单击按Recompile <ws>.scRun.sc` 的工作表,它起作用了...哦,工作表好!

【讨论】:

  • 即使将T 更改为Int- 标志上也会出现红色。这应该是一个不同的问题。
  • 你是对的。需要明确参数化事物:)
猜你喜欢
  • 2018-04-16
  • 2014-08-22
  • 2014-11-17
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多