Valid usages of implicit parameters

穿精又带淫゛_ 提交于 2019-12-05 16:06:43

This is very much a fine use case. I actually recommend this when scope determines the parameter to use. It provides an elegant way to pass some sort of context into a Plugin class so that utility functions will use the context. For example:

trait Context

object UtilityLib {
  def performHandyFunction(implicit x : Context) : SomeResult = ...
}

trait Plugin {
   def doYourThing(implicit ctx : Context) : Unit
}

class MyPlugin extends Plugin {
  def doYourThing(implicit ctx : Context) : Unit = {
    UtilityLib.performHandyFunction
  }
}

SomePluginAPI.register(new MyPlugin)

You can see an example in a database migration system I was toying. Check out the Migration class and its MigrationContext.

It doesn't really look like an idiomatic use of implicits, which tend to be suited for type classes and dependency injection. There's absolutely no point in passing about a class with no members...

It's also more common to define an implicit val or object of type I before making the call to (new B).foo

Having said all that, you supplied an obviously a very abstract example. So it's not too hard to imagine a reasonable use-case for implicits that follows a similar pattern.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!