Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

syntactic sugar - 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…

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...