scala - How to use implicit value with out passing it in to function? -
i under assumption if, somewhere in system, there value marked implicit:
implicit val moo = "world!"
then 'plucked air' whenever , wherever needed?
is correct?
so if have following code:
import execution.implicits._ def myfunc(stub:string)(implicit imp:string) = { //the compiler knows imp should same moo println(stub + " " + imp) } myfunc("hello") // <- should print "hello world!"
however, how can avoid having define signature of function taking implicit? means way call chain have include in parameters not fit intended usefulness of implicits. how can genuinely 'pluck air'?
thanks
in short, can't.
here options:
forwarding implicits
say have function executes future
, need executioncontext
: can either import scala.concurrent.executioncontext.implicits.global
(or define own etc) in same file somefun
, , this:
import scala.concurrent.executioncontext.implicits.global def somefun(): future[something] = { future(something) }
or if don't want import in same file(class, object etc) somefun
, forward implicit. way, can import when use somefun
in file.
def somefun()(implicit ex: executioncontext): future[something] { future(something) }
context bounds
sounds want, didn't implement properly.
class stub[t](name: string) def myfunc[t: moo](stub: stub[t]) = { println(stub + " " + implicitly[moo[string]]) }
the above equivalent of:
def myfunc[t](stub: t)(implicit evidence: moo[t]) = { println(stub + " " + evidence.tostring) }
view bounds
alternatively, if makes more sense implicitly convert stub
moo
rather bound it:
def myfunc[t <% moo](stub: t) = { println(stub + " " + implicitly[moo[t]]) }
to use above, need provide materialized implicits(e.g way convert stub moo). example:
implicit def stubtomoo[t](stub: stub[t]): moo[t] = { new moo(stub) // or whatever }
bottom line, in question usage of implicits makes no sense whatsoever. can "thin-air" import describe, based on options above, see if it's worth it.
Comments
Post a Comment