Please don’t say “don’t do that”

By Greg Turnquist

Greg L. Turnquist worked on the Spring team for over thirteen years and is a senior staff technical content engineer at Cockroach Labs. He was the lead for Spring Data JPA and Spring Web Services. He wrote Packt's best-selling title, Learning Spring Boot 2.0 2nd Edition, and its 3rd Edition follow-up along many others.

August 24, 2011

I have been digging for a couple of days on how to build a Scala List inside Java. The blog entries are hard to find. Most talk about converting a java.util.List into a Scala List from inside Scala. That is not what I’m looking for, but what really infuriated me was reading a blog entry that told me to just not do it.

I’ll show you how to do what you want in a second, but first, and importantly, I need to explain that what you actually want to do is NOT convert a Java List to a Scala List. Why? It’s because, despite the name similarity, they’re actually very different things…

That is really annoying. Please don’t tell me what to do and not do, okay?

  • I know that there are gaping differences between java.util.List’s interface scala.collections.immutable.List’s concrete implementation.
  • I know that they are backed by different structures. 

That doesn’t change the fact that to embed Scala’s compiler into my Java project, I need to access which requires that I enter certain parameters as a scala.collections.immutable.List.

This was really annoying, and sounded very similar to the answer I often see when people are seeking help on writing multi-threaded coding in Python. “Don’t write multi-threaded. You are probably doing it wrong.” Sorry, but eventually, most people have to write some multi-threaded code. That answer in the sounds a lot like saying “you will hit the GIL and have all kinds of problems, because Python wasn’t built for multi-threading. And we aren’t removing the GIL.” I find that approach equally annoying. It’s one reason I watch the blogs from PyPy, since it seems the only viable way to remove the GIL from Python.

To cut to the chase, it’s not that hard to build an immutable list in Java. Look below.

The key part is Nil.$colon$colon(“dce”). That is the same as saying “dce” :: Nil in pure Scala. The whole block is showing how to embed the Scala compiler (2.9.1) inside Java, configured with –usejavacp -Ystop-after:dce -debug, and then compiling a string of code (not a file).

All you need to remember is that 1 :: 2 :: 3 :: Nil translates to Nil.::(3.::(2.::(1))). Given that, you can probably figure out many Scala interop issues.


Submit a Comment

Your email address will not be published. Required fields are marked *