Consider following code snippet:
object Example {
def run(f: => Unit): Unit = {
implicit val i = 1
f
}
def caller(): Unit =
run {
todo
}
def todo(implicit i: Int): Unit =
println(i)
}
which currently is not compiling with following message:
Error:(14, 13) could not find implicit value for parameter i: Int
todo
^
My question is it possible to make implicit parameter available to call-by-name function body?
EDIT
I tried make it working with macro implementation as suggested by Alexey Romanov
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
object Macros {
def run(f: => Unit): Unit = macro runImpl
def runImpl(c : Context)(f: c.Tree) = {
import c.universe._
q"""{
implicit val i: Int = 3
$f
}"""
}
}
object Example extends App {
Macros.run {
todo
}
def todo(implicit i: Int): Unit =
println(i)
}
Debugging macro i can see that it is correctly expanded into
{
implicit val i: Int = 3
Example.this.todo
}
Unfortunately it does not compiles as well with same error that implicit is not found.
Digging into issue i found discussions here and jira issues https://issues.scala-lang.org/browse/SI-5774
So question is the same: Is it possible to tunnel implicit into todo function in this case?
Simply said - no. implicit requires that it is obvious from the code what is going on. If you want anything to be passed to a function implicitly, it must have implicit parameter which is not the case of your f function.
This is a great source of wisdom related to implicit:
http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html
My question was more about why implicit defined in run is not tunneled into caller's run body
Because that's simply not how lexical scoping works. It isn't in scope where the body is defined. You have two good alternatives:
def run(f: Int => Unit) = f(1)
run { implicit i =>
todo // can use i here
}
Make run a macro. This should be at least an approximation (adapted from SI-5778), unfortunately I can't test it at the moment:
object Macros {
def run(f: => Unit) = macro runImpl
def runImpl(c : Context)(f: c.Tree) = q"""{
implicit val i: Int = 1
// some other implicits
$f
}"""
}
Related
I'm trying to remove some of the boilerplate in an API I am writing.
Roughly speaking, my API currently looks like this:
def toEither[E <: WrapperBase](priority: Int)(implicit factory: (String, Int) => E): Either[E, T] = {
val either: Either[String, T] = generateEither()
either.left.map(s => factory(s, priority))
}
Which means that the user has to generate an implicit factory for every E used. I am looking to replace this with a macro that gives a nice compile error if the user provided type doesn't have the correct ctor parameters.
I have the following:
object GenericFactory {
def create[T](ctorParams: Any*): T = macro createMacro[T]
def createMacro[T](c: blackbox.Context)(ctorParams: c.Expr[Any]*)(implicit wtt: WeakTypeType[T]): c.Expr[T] = {
import c.universe._
c.Expr[T](q"new $wtt(..$ctorParams)")
}
}
If I provide a real type to this GenericFactory.create[String]("hey") I have no issues, but if I provide a generic type: GenericFactory.create[E]("hey") then I get the following compile error: class type required by E found.
Where have I gone wrong? Or if what I want is NOT possible, is there anything else I can do to reduce the effort for the user?
Sorry but I don't think you can make it work. The problem is that Scala (as Java) uses types erasure. It means that there is only one type for all generics kinds (possibly except for value-type specializations which is not important now). It means that the macro is expanded only once for all E rather then one time for each E specialization provided by the user. And there is no way to express a restriction that some generic type E must have a constructor with a given signature (and if there were - you wouldn't need you macro in the first place). So obviously it can not work because the compiler can't generate a constructor call for a generic type E. So what the compiler says is that for generating a constructor call it needs a real class rather than generic E.
To put it otherwise, macro is not a magic tool. Using macro is just a way to re-write a piece of code early in the compiler processing but then it will be processed by the compiler in a usual way. And what your macro does is rewrites
GenericFactory.create[E]("hey")
with something like
new E("hey")
If you just write that in your code, you'll get the same error (and probably will not be surprised).
I don't think you can avoid using your implicit factory. You probably could modify your macro to generate those implicit factories for valid types but I don't think you can improve the code further.
Update: implicit factory and macro
If you have just one place where you need one type of constructors I think the best you can do (or rather the best I can do ☺) is following:
Sidenote the whole idea comes from "Implicit macros" article
You define StringIntCtor[T] typeclass trait and a macro that would generate it:
import scala.language.experimental.macros
import scala.reflect.macros._
trait StringIntCtor[T] {
def create(s: String, i: Int): T
}
object StringIntCtor {
implicit def implicitCtor[T]: StringIntCtor[T] = macro createMacro[T]
def createMacro[T](c: blackbox.Context)(implicit wtt: c.WeakTypeTag[T]): c.Expr[StringIntCtor[T]] = {
import c.universe._
val targetTypes = List(typeOf[String], typeOf[Int])
def testCtor(ctor: MethodSymbol): Boolean = {
if (ctor.paramLists.size != 1)
false
else {
val types = ctor.paramLists(0).map(sym => sym.typeSignature)
(targetTypes.size == types.size) && targetTypes.zip(types).forall(tp => tp._1 =:= tp._2)
}
}
val ctors = wtt.tpe.decl(c.universe.TermName("<init>"))
if (!ctors.asTerm.alternatives.exists(sym => testCtor(sym.asMethod))) {
c.abort(c.enclosingPosition, s"Type ${wtt.tpe} has no constructor with signature <init>${targetTypes.mkString("(", ", ", ")")}")
}
// Note that using fully qualified names for all types except imported by default are important here
val res = c.Expr[StringIntCtor[T]](
q"""
(new so.macros.StringIntCtor[$wtt] {
override def create(s:String, i: Int): $wtt = new $wtt(s, i)
})
""")
//println(res) // log the macro
res
}
}
You use that trait as
class WrapperBase(val s: String, val i: Int)
case class WrapperChildGood(override val s: String, override val i: Int, val float: Float) extends WrapperBase(s, i) {
def this(s: String, i: Int) = this(s, i, 0f)
}
case class WrapperChildBad(override val s: String, override val i: Int, val float: Float) extends WrapperBase(s, i) {
}
object EitherHelper {
type T = String
import scala.util._
val rnd = new Random(1)
def generateEither(): Either[String, T] = {
if (rnd.nextBoolean()) {
Left("left")
}
else {
Right("right")
}
}
def toEither[E <: WrapperBase](priority: Int)(implicit factory: StringIntCtor[E]): Either[E, T] = {
val either: Either[String, T] = generateEither()
either.left.map(s => factory.create(s, priority))
}
}
So now you can do:
val x1 = EitherHelper.toEither[WrapperChildGood](1)
println(s"x1 = $x1")
val x2 = EitherHelper.toEither[WrapperChildGood](2)
println(s"x2 = $x2")
//val bad = EitherHelper.toEither[WrapperChildBad](3) // compilation error generated by c.abort
and it will print
x1 = Left(WrapperChildGood(left,1,0.0))
x2 = Right(right)
If you have many different places where you want to ensure different constructors exists, you'll need to make the macro much more complicated to generate constructor calls with arbitrary signatures passed from the outside.
The use cases for implicit macros is supposed to be the so-called "materialisation" of type class instances.
Unfortunately, the example in the documentation is a bit vague on how that is achieved.
Upon being invoked, the materializer can acquire a representation of T and generate the appropriate instance of the Showable type class.
Let's say I have the following trait ...
trait PrettyPrinter[T]{
def printed(x:T) : String
}
object PrettyPrinter{
def pretty[T](x:T)(implicit pretty:PrettyPrinter[T]) = pretty printed x
implicit def prettyList[T](implicit pretty :PrettyPrinter[T]) = new PrettyPrinter[List[T]] {
def printed(x:List[T]) = x.map(pretty.printed).mkString("List(",", ",")")
}
}
and three test classes
class A(val x:Int)
class B(val x:Int)
class C(val x:Int)
Now I understand that instead of writing the following boilerplate
implicit def aPrinter = new PrettyPrinter[A] {def printed(a:A) = s"A(${a.x})"}
implicit def bPrinter = new PrettyPrinter[B] {def printed(b:B) = s"B(${b.x})"}
implicit def cPrinter = new PrettyPrinter[C] {def printed(c:C) = s"C(${c.x})"}
we should be able to add
implicit def materialise[T] : PrettyPrinter[T] = macro implMaterialise[T]
def implMaterialise[T](c:blackbox.Context):c.Expr[PrettyPrinter[T]] = {
import c.universe._
???
}
to the object PrettyPrinter{...} which then generates the corresponding PrettyPrinters on demand ... how? How do I actually get that "representation of T"?
If I try c.typeOf[T], for example, "No TypeTag available for T".
UPDATE
Trying to use class tags doesn't seem to work either.
implicit def materialise[T:ClassTag] : PrettyPrinter[T] = macro implMaterialise[T]
def implMaterialise[T:ClassTag](c:blackbox.Context):c.Expr[PrettyPrinter[T]] = {
import c.universe._
???
}
results in
Error:(17, 69) macro implementations cannot have implicit parameters other than WeakTypeTag evidences
implicit def materialise[T:ClassTag] : PrettyPrinter[T] = macro implMaterialise[T]
^
update2
Interestingly, using WeakTypeTags doesn't really change anything as
implicit def materialise[T:WeakTypeTag]: PrettyPrinter[T] = macro implMaterialise[T]
def implMaterialise[T](c:blackbox.Context)(implicit evidence : WeakTypeTag[T]):c.Expr[PrettyPrinter[T]]
= {
import c.universe._
???
}
will result in
Error:(18, 71) macro implementations cannot have implicit parameters other than WeakTypeTag evidences
implicit def materialise[T:WeakTypeTag]: PrettyPrinter[T] = macro implMaterialise[T]
^
How do I actually get that "representation of T"?
You need to use c.WeakTypeTag, as hinted at by the compiler message you found in your "UPDATE" section.
This project has a working example that you can adapt: https://github.com/underscoreio/essential-macros/blob/master/printtype/lib/src/main/scala/PrintType.scala
object PrintTypeApp extends App {
import PrintType._
printSymbol[List[Int]]
}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.util.{ Try => ScalaTry }
object PrintType {
// Macro that generates a `println` statement to print
// declaration information of type `A`.
//
// This only prints meaningful output if we can inspect
// `A` to get at its definition:
def printSymbol[A]: Unit =
macro PrintTypeMacros.printTypeSymbolMacro[A]
}
class PrintTypeMacros(val c: Context) {
import c.universe._
def printTypeSymbolMacro[A: c.WeakTypeTag]: c.Tree =
printSymbol(weakTypeOf[A].typeSymbol, "")
}
This question already has an answer here:
Implicit parameter for literal function
(1 answer)
Closed 6 years ago.
Most of the play framework I see the block of code
// Returns a tasks or an 'ItemNotFound' error
def info(id: Long) = SecuredApiAction { implicit request =>
maybeItem(Task.findById(id))
}
yes my understanding is define a method info(id: Long) and in scala doc to create function in scala the syntax look like this:
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
Can you tell me what is the meaning of implicit request => and SecuredApiAction put before {
play.api.mvc.Action has helper methods for processing requests and returning results. One if it's apply overloads accepts a play.api.mvc.Request parameter:
def apply(request: Request[A]): Future[Result]
By marking the request parameter as implicit, you're allowing other methods which implicitly require the parameter to use it. It also stated in the Play Framework documentation:
It is often useful to mark the request parameter as implicit so it can
be implicitly used by other APIs that need it.
It would be same if you created a method yourself and marked one if it's parameters implicit:
object X {
def m(): Unit = {
implicit val myInt = 42
y()
}
def y()(implicit i: Int): Unit = {
println(i)
}
}
Because there is an implicit in scope, when invoking y() the myInt variable will be implicitly passed to the method.
scala> :pa
// Entering paste mode (ctrl-D to finish)
object X {
def m(): Unit = {
implicit val myInt = 42
y()
}
def y()(implicit i: Int): Unit = {
println(i)
}
}
// Exiting paste mode, now interpreting.
defined object X
scala> X.m()
42
Suppose that I have the following scala code:
trait ValueSource[A] {
def value(a: Int): A
}
trait ValueSourceOps[A] {
def self: Int
def F: ValueSource[A]
def value: A = F.value(self)
}
trait ToValueSourceOps {
implicit def toValueSourceOps[A](index: Int)(implicit F0: ValueSource[A]): ValueSourceOps[A] = new ValueSourceOps[A] {
def self = index
def F: ValueSource[A] = F0
}
}
object Test extends ToValueSourceOps {
def value[A: ValueSource](index: Int): A = toValueSourceOps(index).value
}
The code above compiles well, but when I change the last line (body of method "value" in object Test) to
def value[A: ValueSource](index: Int): A = index.value
the compiler complains that
could not find implicit value for parameter F0: ValueSource[A]
In my opinion, def value[A: ValueSource] means I have a implicit value "ValueSource[A]", then why does the compilation fail?
The A in toValueSourceOps has no relationship with the A in value, which makes inferring it problematic. To me the real question is why it works when you call the method explicitly.
I'm guessing that, when toValueSourceOp is called explicitly, it has to infer the same A because that's the only implicit available.
Is there a way to pass an implicit parameter into a curried function. I am using a dirty fix (se below) but it is not pretty. I would love to be able to pass the implicit var "i" as a implicit param.
case class myLoaner() {
implicit val i = "How to get this val into scope within the session function"
def withCode[T](session: => T): Either[Exception, T] = {
try {
Right(session)
} catch {
case ex: Exception => {
Left(ex)
}
}
}
}
object Test {
def main(args: Array[String]) {
val r = myLoaner()
r.withCode {
implicit val imp = r.i // I want to get rid of this line of code and use the implict val defined above directly
val h = new Helper
h.run
}
}
class Helper {
def run(implicit i: String) {
println(i)
}
}
}
After val r = myLoaner(), you can write
import r.i
or
import r._
to do what you want. Alternatively, you can mark r itself implicit and provide this extra definition:
implicit def loanerString(implicit loaner: myLoaner): String = loaner.i
... but now a little bit too many implicits start floating around for my taste, so use that wisely. Sometimes too much implicit magic harms the readability and understandability of your code.
You can always pass implicit parameters directly, e.g. as h.run(r.i).