在 Scala 中,如何将导入语句传递给子类? [英] In Scala, how do I pass import statements through to subclasses?

查看:49
本文介绍了在 Scala 中,如何将导入语句传递给子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

object TimeHelpers {def seconds(in: Long): Long = in * 1000L}导入 TimeHelpers._类基{秒(1000L)}//单独的文件类 Base2 扩展 Base {//不编译//秒(1000L)}

我是否必须为 Base2 手动导入,或者有没有办法自动导入?

解决方案

没有这样的机制,抱歉.

不过,一个技巧是使用 trait 继承而不是导入.这可能是对多个导入进行分组的有用方法.例如,

trait Helpers1 {def seconds(in: Long): Long = in * 1000L}特质助手2 {def millis(in: Long): Long = in * 1000000L}类基{受保护的对象助手使用 Helpers2 扩展 Helpers1}//单独的文件类 Base2 扩展 Base {//可以限定对辅助函数的引用:helpers.seconds(1000L)helpers.millis(1000L)//或者,可以在一行中导入多个辅助特征:导入助手._秒(1000L)毫厘(1000L)}

另一种可能性是让 Base 继承 Helpers1 和 Helpers2,但是您可能希望这些方法受到保护.>

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?

解决方案

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.

这篇关于在 Scala 中,如何将导入语句传递给子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆