开发者

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

开发者 https://www.devze.com 2023-04-01 02:36 出处:网络
For example object TimeHelpers { def seconds(in: Long): Long = in * 1000L } import TimeHelpers._ class Base {

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 t开发者_如何学Pythonhis?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消