Last active
January 26, 2022 22:03
-
-
Save vivekragunathan/d05d904007237d6835540a14d4d23809 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Real code is down below (scroll): | |
| // Reading the scala 3 documentation on macros (https://docs.scala-lang.org/scala3/guides/macros/macros.html) and trying out this example in that page: | |
| /* | |
| // ----- inspect.scala | |
| def inspectCode(x: Expr[Any])(using Quotes): Expr[Any] = | |
| println(x.show) | |
| x | |
| inline def inspect(inline x: Any): Any = ${ inspectCode('x) } | |
| // ------ main.scala | |
| object main extends App { println(inspect(2+3)) } | |
| **/ | |
| // The documentation says: | |
| // The following macro implementation simply prints the expression of the provided argument... | |
| // I was under the impression that the main code will print `2 + 3` instead of evaluating the | |
| // expression and printing `5`. What am I missing? | |
| // Same is the case with another example on the page: | |
| // Calling our inspect macro inspect(sys error "abort") prints a string representation of the argument expression at compile time: scala.sys.error("abort") | |
| // But passing `error("abort")` to `inspect` throws an exception and aborts. | |
| import scala.quoted.* | |
| object InspectCode: | |
| inline def apply(inline x: Any) = ${ inspectCode('x) } | |
| private def inspectCode(x: Expr[Any])(using Quotes): Expr[Any] = | |
| println(x.show) | |
| x | |
| object InspectCodeByName: | |
| inline def apply(inline x: => Any) = ${ inspectCodeByName('x) } | |
| private def inspectCodeByName(x: Expr[Any])(using Quotes): Expr[Any] = | |
| println(x.show) | |
| x |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All of the above calls evaluate the passed expression to a value instead of printing the expression as mentioned in the Scala 3 macros documentation. Or what am I reading wrong and misunderstanding?