在SPARK REPL上给出错误(对A的引用是不明确的)并且在Intellij和Scala REPL中工作正常吗?

时间:2016-11-24 07:16:55

标签: scala class apache-spark read-eval-print-loop companion-object

我有一个示例代码:

    class A(str: String) {
  println(s"InsideCase:::$str")
}

object A {
  def apply(str: String) = {
    println("foobar::")
    new A(str)
  }
}

object b extends App {
  A("kool")
}

此代码在Intellij中运行良好。并给我输出:

foobar::
InsideCAse:::kool

但是当尝试在REPL上执行此操作时:

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

class A(str: String) {
  println(s"InsideCAse:::$str")
}

object A {
  def apply(str: String) = {
    println("foobar::")
    new A(str)
  }
}


// Exiting paste mode, now interpreting.

defined class A
defined object A

scala> A("kool")

它给了我以下错误:

<console>:27: error: reference to A is ambiguous;
it is imported twice in the same scope by
import $line31$read.A
and import INSTANCE.A
       A("kool")

我在这里缺少什么?如果你能详细解释一下会有所帮助。

1 个答案:

答案 0 :(得分:2)

这是Spark REPL限制。您可以使用对象包装器以旧式学校方式执行此操作:

object awrapper {

  class A(str: String) {
    println(s"InsideCAse:::$str")
  }

  object A {
    def apply(str: String) = {
      println("foobar::")
      new A(str)
    }
  }
}

import awrapper._

或使用paste -raw定义包(Scala 2.11 +):

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

package apacakage

class A(str: String) {
  println(s"InsideCAse:::$str")
}

object A {
  def apply(str: String) = {
    println("foobar::")
    new A(str)
  }
}


// Exiting paste mode, now interpreting.


scala> import apacakage._
import apacakage._

scala> A("kool")
foobar::
InsideCAse:::kool
res1: apacakage.A = apacakage.A@6e818345