How to read files from resources folder in Scala?

Resources in Scala work exactly as they do in Java. It is best to follow the Java best practices and put all resources in src/main/resources and src/test/resources. Example folder structure: testing_styles/ ├── build.sbt ├── src │   └── main │   ├── resources │   │   └── readme.txt Scala 2.12.x && 2.13.x reading a resource To read resources … Read more

Stream vs Views vs Iterators

First, they are all non-strict. That has a particular mathematical meaning related to functions, but, basically, means they are computed on-demand instead of in advance. Stream is a lazy list indeed. In fact, in Scala, a Stream is a List whose tail is a lazy val. Once computed, a value stays computed and is reused. … Read more

What type to use to store an in-memory mutable data table in Scala?

You could use a mutable.Map[TupleN[A1, A2, …, AN], R] , or if memory is a concern, a WeakHashMap[1]. The definitions below (built on the memoization code from michid’s blog) allow you to easily memoize functions with multiple arguments. For example: import Memoize._ def reallySlowFn(i: Int, s: String): Int = { Thread.sleep(3000) i + s.length } … Read more

Convert java.util.HashMap to scala.collection.immutable.Map in java

It’s entirely possible to use JavaConverters in Java code—there are just a couple of additional hoops to jump through: import java.util.HashMap; import scala.Predef; import scala.Tuple2; import scala.collection.JavaConverters; import scala.collection.immutable.Map; public class ToScalaExample { public static <A, B> Map<A, B> toScalaMap(HashMap<A, B> m) { return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap( Predef.<Tuple2<A, B>>conforms() ); } public static HashMap<String, String> example() { … Read more

When should I choose Vector in Scala?

As a general rule, default to using Vector. It’s faster than List for almost everything and more memory-efficient for larger-than-trivial sized sequences. See this documentation of the relative performance of Vector compared to the other collections. There are some downsides to going with Vector. Specifically: Updates at the head are slower than List (though not … Read more

What is the difference between JavaConverters and JavaConversions in Scala?

EDIT: Java Conversions got @deprecated in Scala 2.13.0. Use scala.jdk.CollectionConverters instead. JavaConversions provide a series of implicit methods that convert between a Java collection and the closest corresponding Scala collection, and vice versa. This is done by creating wrappers that implement either the Scala interface and forward the calls to the underlying Java collection, or … Read more