Scala Error: trait exists, but it has no companion object
Scala Error: trait exists, but it has no companion object
我遇到的情况与下面类似:
package A
trait A1{
def a2 = 0
}
package B
trait B1{
def b2 = {
import A.A1._ // Error: trait A1 exists, but it has no companion object
a2
}
}
这可能不是很好的设计,但将来会更改。有没有办法解决这个错误?
您不能从特征定义中导入。但是可以从特征定义的实例中导入。 A1
是特质
问题
import A.A1._
以上说法不成立。当导入 A.A1._
时,Scala 编译器正在寻找对象 A1
但 A1
是特征,没有 A1
可用。所以它抱怨 A1
trait 没有伴随对象。
Companion object is the object with the same name as class/trait definition
如果要将特征 A1
(特征定义)导入范围。就这样
import A.A1
您可以导入 object/companion 对象的内部结构
object Bar {
val x = 1
}
import Bar._
现在 x
在范围内可用
如果 Foo
是对象那么 import Foo._
是有效的
Scala REPL
scala> trait A { val a = 1}
defined trait A
scala> val foo = new A{}
foo: A = $anon@9efcd90
scala> import foo._
import foo._
scala> a
res0: Int = 1
我遇到的情况与下面类似:
package A
trait A1{
def a2 = 0
}
package B
trait B1{
def b2 = {
import A.A1._ // Error: trait A1 exists, but it has no companion object
a2
}
}
这可能不是很好的设计,但将来会更改。有没有办法解决这个错误?
您不能从特征定义中导入。但是可以从特征定义的实例中导入。 A1
是特质
问题
import A.A1._
以上说法不成立。当导入 A.A1._
时,Scala 编译器正在寻找对象 A1
但 A1
是特征,没有 A1
可用。所以它抱怨 A1
trait 没有伴随对象。
Companion object is the object with the same name as class/trait definition
如果要将特征 A1
(特征定义)导入范围。就这样
import A.A1
您可以导入 object/companion 对象的内部结构
object Bar {
val x = 1
}
import Bar._
现在 x
在范围内可用
如果 Foo
是对象那么 import Foo._
是有效的
Scala REPL
scala> trait A { val a = 1}
defined trait A
scala> val foo = new A{}
foo: A = $anon@9efcd90
scala> import foo._
import foo._
scala> a
res0: Int = 1