【问题标题】:Scala interpreter can't find my class?Scala 解释器找不到我的课程?
【发布时间】:2011-12-13 07:14:00
【问题描述】:

我正在尝试在解释器中加载一个 Scala 文件:

trait MyOrdered {
  def <(that: MyInt):Boolean = compare(that) < 0
  def >(that: MyInt):Boolean = compare(that) > 0
  def <=(that: MyInt):Boolean = compare(that) < 0 || this == that
  def >=(that: MyInt):Boolean = compare(that) > 0 || this == that
  def compare(that: MyInt): Int
}

class MyInt(val value: Int) extends MyOrdered {
  def compare(that: MyInt) =
    if (this.value < that.value) -1 
    else if (this.value == that.value) 0
    else 1
}


object App extends Application{
  val a = new MyInt(2)
  val b = new MyInt(4)
  println(a < b)
  println(a > b)
}

但我收到一个愚蠢的错误:

Loading traits.scala...
<console>:8: error: not found: type MyInt
         def <(that: MyInt):Boolean = compare(that) < 0
                     ^
<console>:12: error: not found: type MyInt
         def compare(that: MyInt): Int

我怎样才能让解释器知道 MyInt 类,这是在路上定义的?

【问题讨论】:

    标签: scala types polymorphism


    【解决方案1】:

    我想你想要:paste 的行为。 :load 的行为就像您在解释器中输入一样,即,它会在找到右大括号后立即进行解释。您可以通过将代码包装在这样的对象中来模拟:paste:

    object Test {
      trait MyOrdered {
    def <(that: MyInt):Boolean = compare(that) < 0
    def >(that: MyInt):Boolean = compare(that) > 0
    def <=(that: MyInt):Boolean = compare(that) < 0 || this == that
    def >=(that: MyInt):Boolean = compare(that) > 0 || this == that
    def compare(that: MyInt): Int
    }
    
    class MyInt(val value: Int) extends MyOrdered {
      def compare(that: MyInt) =
      if (this.value < that.value) -1 
      else if (this.value == that.value) 0
      else 1
    }
    
    
    object App extends Application{
      val a = new MyInt(2)
      val b = new MyInt(4)
      println(a < b)
      println(a > b)
     }
    }
    

    现在您可以在:load Test.scala 和import Test._ 之后随意使用它

    【讨论】:

    • 好的,谢谢。我认为对整个文件进行分析,而不是逐类分析。 :paste 也能正常工作。
    猜你喜欢
    • 2016-12-02
    • 2020-12-23
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多