1

I was playing around with scala lifting and I accidentally discovered that Scala seems has some sort of implicit support for lambda expressions.

import scala.reflect.Code
import scala.reflect.Function
import scala.reflect.Select

object Test {
  trait Foo {
    def aMethod : String
  }

  val ast : Code[_] = (f:Foo) => f.aMethod 

  //now you can pattern match the AST 
  val Function(_, Select(_, symbol))= ast.tree
  val nameOfAMethod = symbol.name
  println(nameOfAMethod) //prints "aMethod"
}

ast will have the AST for the lambda on the right hand side.

It seems not to work for literals, so:

val ast : Code[_] = 42

does not work.

But this does :

val ast : Code[_] = () => 42

I can't seem to find documentation for it. There doesn't seem to be any implicit conversion active. How does this work?

Régis Jean-Gilles
  • 32,541
  • 5
  • 83
  • 97
Maxm007
  • 1,190
  • 2
  • 13
  • 21
  • 2
    You must be missing something because on my side it won't compile. That's assuming `trait Code[T]`. It could be some custom implicits in your code that were doing this conversion for you. – Nikita Volkov Oct 10 '12 at 11:14
  • 2
    Please please please mention your imports. – missingfaktor Oct 10 '12 at 11:36
  • @NikitaVolkov I think he means `scala.reflect.Code`. – Alexey Romanov Oct 10 '12 at 11:36
  • 2
    The source for `Code` says `/** This type is required by the compiler and should not be used in client code. */`. So it looks like some kind of special case for the compiler. I would not worry about it and follow the advice that you should not use it. – Luigi Plinge Oct 10 '12 at 13:27
  • I'm not worried about it. I like it! It's like Expression<> in C# ;) – Maxm007 Oct 10 '12 at 13:30
  • 2.10 will contain a full(er) reflection API (behind an experimental flag). RC1 for that may be as soon as next week. You might like to try it out. – Brian Smith Oct 10 '12 at 15:27
  • Yes, we will be upgrading to 2.10 at some point. In the mean time we're using scala.reflect._ w – Maxm007 Oct 10 '12 at 16:17

0 Answers0