我试图在解释器中加载一个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
类,它是在路上定义的?
我认为你想要: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._
之后随意使用