简体   繁体   中英

scala: import functions defined inside implicit class

I want to attach static utilities to those classes that extend a trait called 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)
  }
}

Now the following works fine:

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")

}

But I am too greedy, how do I covert the call

val test = app.getString("hello")

Into

val test = getString("hello")

You can explicitly convert the app:Application to appWithConfig:AppConfig and import all methods of the appWithConfig:AppConfig

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

The best option I had was to reference the methods in the parent object:

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)

  }
}

Then I was able to invoke as below:

object TestAppConf extends App {

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

  val test = getString("hello")

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM