Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - mixing in a trait with its imports (inheriting imports)

I have the following code:

trait A {
  import org.somepackage.C._
}

class B extends A {
  def getValue = value
                 ^^^^^
}

object C {
  var value = 5
}

The value in class B is not visible what means that the inherent import of class A was not inherited by B, although the value is perfectly visible inside A. How to achieve the effect of also inheriting imports so I could avoid explicitly importing same things in multiple classes where trait A mixes in?

like image 224
noncom Avatar asked Feb 16 '12 08:02

noncom


1 Answers

Imports not being a first class entity do not exhibit the behavior you are expecting. You can instead restructure your design thusly to achieve something close:

trait A with C {

}

class B extends A {
  def getValue = value // Now this will work.
}

trait C {
  var value = 5
}

object C extends C

This idiom is used in Scalaz 6 to tax users with as few imports as possible.

like image 117
missingfaktor Avatar answered Oct 31 '22 14:10

missingfaktor