Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language integrated query in Kotlin?

Tags:

linq

kotlin

I'm working on porting to Kotlin one of my on C# projects which uses certain features of linq. As an example lets take the following linq query:

from a in A
from b in B
from c in C
select fun(a,b,c);

In C# this allows to chain functions of any type then collect the results in an easy to read way which is preetty much may requirement. This is equivalent (more or less) to:

A.SelectMany(a => B, (a, b) => new {a, b}).SelectMany(t => C, (t, c) => fun( t.a, t.b, c));

It is not a problem to achieve functionality of Enumerable.SelectMany in Kotlin but it is still as noisy as the C# equivalent.

Is there any way to achieve something similar in Kotlin without fiddling explicilty with nested tuples but closer to the linq?

like image 214
Michal Pawluk Avatar asked May 24 '18 12:05

Michal Pawluk


1 Answers

Marko Topolnik provided the following as a comment, but it is actually a valid solution:

A.flatMap { a -> 
    B.flatMap { b -> 
        C.map { c -> 
            fun(a, b, c) 
        } 
    } 
}
like image 196
Robert Jack Will Avatar answered Sep 28 '22 07:09

Robert Jack Will