Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how do I pass import statements through to subclasses?

Tags:

scala

For example

object TimeHelpers {
  def seconds(in: Long): Long = in * 1000L
}

import TimeHelpers._

class Base {

  seconds(1000L)
}

// separate file
class Base2 extends Base {
// does not compile
//seconds(1000L)

}

Do I have to manually import for Base2 or is there a way to automatically do this?

like image 231
deltanovember Avatar asked Aug 31 '11 03:08

deltanovember


People also ask

How do imports work in Scala?

Import in Scala Importing packages in Scala is more flexible than in other languages. We can place import statements anywhere in the code and even hide or rename members of packages when you import them. Note: Users can either import the package as a whole or some of its member methods, classes, etc.

How to define package in Scala?

Creating a package Packages are created by declaring one or more package names at the top of a Scala file. Notice how the users directory is within the scala directory and how there are multiple Scala files within the package. Each Scala file in the package could have the same package declaration.

Where are Scala packages?

Packages are declared as a first statement at the top of a Scala file.


1 Answers

There's no such mechanism, sorry.

One trick, though, is to use trait inheritance rather than imports. This can be a useful way of grouping what would otherwise be multiple imports. For example,

trait Helpers1 {
  def seconds(in: Long): Long = in * 1000L
}

trait Helpers2 {
  def millis(in: Long): Long = in * 1000000L
}

class Base {
  protected object helpers extends Helpers1 with Helpers2
}

// separate file
class Base2 extends Base {
  // References to helper functions can be qualified:
  helpers.seconds(1000L)
  helpers.millis(1000L)

  // Or, can import multiple helper traits with one line:
  import helpers._
  seconds(1000L)
  millis(1000L)
}

Another possibility is to have Base inherit Helpers1 with Helpers2, but then you'd probably want the methods to be protected.

like image 173
Kipton Barros Avatar answered Oct 04 '22 22:10

Kipton Barros