Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent to C#'s Expression API

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.

like image 649
user281655 Avatar asked Jan 21 '10 07:01

user281655


3 Answers

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.

like image 139
Thomas Jung Avatar answered Nov 02 '22 18:11

Thomas Jung


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).

like image 6
Daniel C. Sobral Avatar answered Nov 02 '22 18:11

Daniel C. Sobral


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 _).

like image 2
Rex Kerr Avatar answered Nov 02 '22 18:11

Rex Kerr