[英]scala: import functions defined inside implicit class
I want to attach static utilities to those classes that extend a trait called Application. 我想将静态实用程序附加到那些扩展了称为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 您可以将app:Application显式转换为appWithConfig:AppConfig并导入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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.