2

我有一个示例代码:

    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")

我在这里想念什么?如果可以,请详细解释,这将很有帮助。

4

1 回答 1

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
于 2016-11-24T08:13:19.360 回答