Scala伴侣班级警告

时间:2015-04-10 05:57:10

标签: scala

我是Scala编程新手,有人可以在下面解释我的警告原因吗?

Scala-Companion-Warning 我试图找到原因,这似乎是一个很大的修复:https://issues.scala-lang.org/browse/SI-6439

那么为什么我会收到此警告?

2 个答案:

答案 0 :(得分:12)

这特定于REPL(读取评估打印循环),因为它无法知道用户输入何时结束。

使用:paste解决问题:

scala> class A {}
defined class A

scala> object A {}
defined object A
warning: previously defined class A is not a companion to object A.
Companions must be defined together; you may wish to use :paste mode for this.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class A {}
object A {}

// Exiting paste mode, now interpreting.

defined class A
defined object A

答案 1 :(得分:3)

Companion类及其对象必须在同一个文件中定义。

所以你可以在一个文件中编写你的类和对象,然后在REPL中使用:paste你可以运行你的代码。不会出现警告。

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Student(sid: Int, sname: String) {
    val id = sid
    val name = sname

    override def toString() = this.id + "," + this.name
  }

  object Student {
    def displayDetails(st: Student) = {
      println("Student Details : " + st.id + "," + st.name)
    }
  }


// Exiting paste mode, now interpreting.

defined class Student
defined object Student