Scala companion class warning

2020-03-18 03:39发布

问题:

I am new to Scala programming, can someone explain me below warning reason?

I tried to find the reason and it seems like a big fixed earlier: https://issues.scala-lang.org/browse/SI-6439

So why I am getting this warning?

回答1:

This is specific to the REPL (Read Evaluate Print Loop), since it can't know when user input ends.

Use :paste to get around it :

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


回答2:

Companion class and its object must be defined in the same file.

so you can write your class and object in a file and then using :paste in REPL you can run your code. no warning will appear.

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


标签: scala