Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the desugared part of a Scala for/comprehension expression?

Does anyone know how to get the (Scala part only) desugared translation of a for/comprehension expression before it actually tries to compile in the REPL (or compiler)?

The only thing I've found so far is the compiler "-print" flag but that gives you the full Scala translation…

like image 962
IODEV Avatar asked Mar 27 '12 14:03

IODEV


People also ask

How scala for comprehension works?

Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.

What is Desugaring in Scala?

Scala Language For Expressions Desugaring For Comprehensions for comprehensions in Scala are just syntactic sugar. These comprehensions are implemented using the withFilter , foreach , flatMap and map methods of their subject types.

What is a for comprehension in Scala?

Comprehensions is a construct in Scala which allows us to evaluate certain expressions. The For Comprehension has the form for (enumerators) yield e , where enumerators refer to a semi-colon separated list of enumerators. An enumerator can either be a generator that iterates the list or a filter.

What operations is a for comprehension syntactic sugar for?

Finally, we discovered that a for-comprehension is just syntactic sugar for a sequence of calls to methods foreach, map, flatMap, and withFilter.


1 Answers

As I already said in the other topic, scalac -print prints out scala code, not java. It translates all scala keywords that are not directly compatible with java to normal scala code. It is not possible to let the compiler translate only parts afaik. But basically a for-comprehension is always translated the same way.

A simple for/yield like this

for(x <- List(1,2,3)) yield x*x 

will be translated to

List(1,2,3).map {x => x*x} 

And without yield

for(x <- List(1,2,3)) println(x) 

to

List(1,2,3).foreach{x => println(x)} 

Nested fors will be translated to nested flatMap/map constructs

for(x <- List(1,2,3); y <- List(4,5,6)) yield x*y 

will be translated to

List(1,2,3).flatMap { x =>   List(4,5,6).map { y =>     x*y   } } 

So there is absolutely no magic

like image 159
drexin Avatar answered Sep 28 '22 19:09

drexin