如何在定义之前调用类

时间:2016-08-05 07:50:06

标签: scala

我是Scala的新手,首先阅读Scala By Example本书,

该书中存在一个问题,我无法理解,例如第59页,作者写道:

abstract class Stack[+A] {
  def push[B >: A](x: B): Stack[B] = new NonEmptyStack(x, this)
  def isEmpty: Boolean
  def top: A
  def pop: Stack[A]
}
object EmptyStack extends Stack[Nothing] {
  def isEmpty = true
  def top = error("EmptyStack.top")
  def pop = error("EmptyStack.pop")
}
class NonEmptyStack[+A](elem: A, rest: Stack[A]) extends Stack[A] {
  def isEmpty = false
  def top = elem
  def pop = rest
}

如您所见,在定义之前调用 NonEmptyStack(x,this)类。 怎么可能?

当我尝试在编译器消息下面遇到的那些代码时:

  

< console>:11:错误:未找到:输入NonEmptyStack
          def push [B>:A](x:B):Stack [B] = new NonEmptyStack(x,this)

2 个答案:

答案 0 :(得分:3)

您需要使用:paste然后复制代码以允许Scala REPL评估整个代码块。

答案 1 :(得分:0)

答案是Sarvesh Kumar Singh's comment

  

嗯....问题是Scala实际上是一种编译语言,只要在项目或类路径中可用,编译器就会找到该类。 - Sarvesh Kumar Singh 8月5日10:51

相关问题