Benefits of LINQ over functional method chaines

c# expression-trees kotlin linq sql


There was a discussion on Kotlin Slack about a possibility of adding code trees to support things like C# LINQ.

In C# LINQ has many applications, but I want to focus on only one (because others a already presumably covered by Kotlin syntax): composing SQL queries to remote databases.


  • We have a data schema of an SQL database expressed somehow in the code so that static tools (or the type system) could check the correctness (at least the naming) of an SQL query

  • We have to generate the queries as strings

  • We want a syntax close to SQL or Java streams

Question: what do expression trees add to the syntax that is so crucial for the task at hand? How good an SQL builder can be without them?

7/6/2016 9:17:11 AM

Popular Answer

How good a query dsl can be without expression trees?

As JINQ has shown you can get very far by analyzing the bytecode to understand the intent of developer and thus translate predicate to SQL. So in principle expression trees are not essential to build a great looking query dsl:

val alices = database.customerStream().where { == "Alice" }

Even without a hackery such as bytecode analysis it's possible to get a decent query dsl with code generation. Querydsl and JOOQ are great examples. With a little bit of Kotlin wrapping code you can then write

val alices = db.findAll(QCustomer.customer, {"Alice") }) 

How do expression trees help building query dsl

Expression tree is a structure representing some code that resolves to a value. By having such structure generated by compiler one does not need bytecode analysis to understand what's the supposed to do. Given the example

val alices = database.customerStream().where { == "Alice" }

The argument to where function would be an expression that we can inspect in runtime and translate it to SQL or other query language. Because the expression trees represent code you don't need to switch between Kotlin and SQL paradigm to write queries. The query code expressed using linq/jinq look pretty much the same regardless if they are executed in memory using POCO/POJO or in the database engine using its query language. The compiler can also do more type checking. Furthermore it's very easy to replace the underlying database with in memory representation to make running tests much faster.

Further reading:

5/23/2017 12:14:44 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow