scala:在隐式类中定义的导入函数

时间:2017-07-06 05:23:54

标签: scala implicit

我想将静态实用程序附加到那些扩展名为Application的特征的类。

trait Application {
    def name: String
}

case class TestApp(name: String) extends Application


object ImplicitConf {
  implicit class AppConfig[T <: Application](val app: T) {

    lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)
  }
}

现在以下工作正常:

import Application, TestApp
import ImplicitConf._
import AppUtil._

object TestAppConf extends App {

  val app: Application = TestApp("TestAppConf")
  val test = app.getString("hello")
  println(s"The Config value is $test")

}

但我太贪心了,我该如何转移电话

val test = app.getString("hello")

进入

val test = getString("hello")

2 个答案:

答案 0 :(得分:0)

您可以显式地将app:Application转换为appWithConfig:AppConfig并导入appWithConfig的所有方法:AppConfig

   val appWithConfig = new AppConfig(app)
   import appWithConfig._

答案 1 :(得分:0)

我最好的选择是引用父对象中的方法:

object ImplicitConf {

  def getString[T <: Application](str: String)(implicit app: T) = AppConfig(app).getString(str)

  implicit class AppConfig[T <: Application](val app: T) {

    @transient lazy val conf = loadConfig


    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)

  }
}

然后我可以调用如下:

object TestAppConf extends App {

  implicit val app: Application = TestApp("TestAppConf")

  val test = getString("hello")

  println(s"The Config value is $test")

}