user1868607
user1868607

Reputation: 2600

Scala Error: trait exists, but it has no companion object

I have a situation similar to the following:

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
 }
}

This may not be good design, but will be changed in the future. Is there a way to get around this error?

Upvotes: 0

Views: 4307

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

You cannot import from trait definition. But can import from the instance of the trait definition. A1 is trait

Problem

import A.A1._ 

The above statement is not valid. When A.A1._ is imported, Scala compiler is looking for the object A1 but A1 is trait, no A1 is available. So it complains A1 trait has no companion object.

Companion object is the object with the same name as class/trait definition

If you want to import trait A1 (trait definition) into scope. Just do

import A.A1

You can import the internals of object/companion object

object Bar {      
  val x = 1    
}

import Bar._

Now x is available in scope

If Foo is the object then import Foo._ is valid

Scala REPL

scala> trait A { val a = 1}
defined trait A

scala> val foo = new A{}
foo: A = $anon$1@9efcd90

scala> import foo._
import foo._

scala> a
res0: Int = 1

Upvotes: 1

Related Questions