views:

289

answers:

4

Is their an equivalent to C#'s Expression API in scala?

For example, I would like to have a lambda like this:

(Foo) => Foo.bar

and be able to access "bar" in the function it is passed to.

+8  A: 

This is not supported by Scala. ScalaQL: Language-Integrated Database Queries for Scala describes a LINQ-like functionality in Scala:

While it is possible for Microsoft to simply extend their language with this particular feature, lowly application developers are not so fortunate. For exam- ple, there is no way for anyone (outside of Sun Microsystems) to implement any form of LINQ within Java because of the language modications which would be required. We faced a similar problem attempting to implement LINQ in Scala.

Fortunately, Scala is actually powerful enough in and of itself to implement a form of LINQ even without adding support for expression trees. Through a combination of operator overloading, implicit conversions, and controlled call- by-name semantics, we have been able to achieve the same eect without making any changes to the language itself.

Thomas Jung
A: 

No, to the best of my knowledge.

Alexey Romanov
+3  A: 

There is an experimental scala.reflect.Code.lift which might be of interest, but the short answer is no, Scala does not have access to the AST in any form (expression trees are a subset of C#'s AST).

Daniel
+2  A: 

It's not quite clear to me what you want. If you want a function that returns a getter for a field, you can do that quite easily:

class Holder(var s: String) { }
class StringSaver(f: Holder => (() => String), h: Holder) {
  val getter = f(h)
  def lookAtString = getter()
}

val held = new Holder("Hello")
val ss = new StringSaver((h: Holder) => (h.s _) , held)
println(ss.lookAtString)
held.s = "Bye now"
println(ss.lookAtString)

The key is to turn the getter h.s into a function via (h.s _).

Rex Kerr