Ranjan Sen
Ranjan Sen

Reputation: 11

Instantiating a class using companion object

Using companion object throws ambiguous reference error in REPL (spark-shell 2.1.0) when an instance of class is initialized (issue 4165 in 1.x.x closed). I see this error in Spark 2.1.0 (see below).

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

class X {
  var m : Long =0
  def add(x: Long): X = {
    m += x
    this 
  }
}
object X {
  def apply(x:Long) = new X().add(x)
}

// Exiting paste mode, now interpreting.

defined class X
defined object X

scala> val v = X(2)
<console>:26: error: reference to X is ambiguous;
it is imported twice in the same scope by
import $line14$read.X
and import INSTANCE.X
       val v = X(2)
               ^

Am I missing something? Thanks

Upvotes: 1

Views: 295

Answers (1)

user7782662
user7782662

Reputation: 31

You cannot define companion object like this in shell. You need either an object wrapper

object myWrapper {
  class X {
    var m: Long = 0
    def add(x: Long): X = {
      m += x
      this 
    }
  }

  object X {
    def apply(x:Long) = new X().add(x)
  }
}

import myWrapper._

Upvotes: 3

Related Questions