score:8

Accepted answer

you can't. only methods can have implicit parameters.

when you do this:

// val f: a => unit = 
{
   implicit a: a => {
     // some action
   }
}

you're actually declaring an anonymous function of type a => unit and you are declaring the argument a as implicit in the function body


you can achieve something close to what you want using the magnet pattern:

class a

case class magnet()
object magnet {
  implicit def fromunit(arg1: unit)(implicit a: a) = magnet()
}

object test extends app {

  implicit val a = new a

  {
    args: magnet => {
      //...
    }
  }.apply()
}

you'll get a deprecation warning though because the magnet must have at least one parameter and i used unit, you should call it like .apply(()) to avoid it

score:3

as said by giovanni: you can't have such a parameter.

however you can use implicitly to resolve implicits within your function:

case class foo(text : string)
implicit val foo = foo("world")

(() => {
  val implfoo : foo = implicitly[foo]
  println(s"hello ${implfoo.text}")
}).apply()

(but to be honest this sounds like it can be written better and you're going into spaghetti code territory with what you're doing.)


Related Query

More Query from same tag