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?
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.
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.
Packages are declared as a first statement at the top of a Scala file.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With