Scala Sets contain the same elements, but sameElements() returns false

The Scala collections library provides specialised implementations for Sets of fewer than 5 values (see the source). The iterators for these implementations return elements in the order in which they were added, rather than the consistent, hash-based ordering used for larger Sets. Furthermore, sameElements (scaladoc) is defined on Iterables (it is implemented in IterableLike – … Read more

What is the differences between Int and Integer in Scala?

“What are the differences between Integer and Int?” Integer is just an alias for java.lang.Integer. Int is the Scala integer with the extra capabilities. Looking in Predef.scala you can see this the alias: /** @deprecated use <code>java.lang.Integer</code> instead */ @deprecated type Integer = java.lang.Integer However, there is an implicit conversion from Int to java.lang.Integer if … Read more

In Scala, what does “view” do?

View produces a lazy collection, so that calls to e.g. filter do not evaluate every element of the collection. Elements are only evaluated once they are explicitly accessed. Now sum does access all elements, but with view the call to filter doesn’t create a full Vector. (See comment by Steve) A good example of the … Read more

How do I pattern match arrays in Scala?

If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following: def processLine(tokens: Array[String]) = tokens match { case Array(_, “”, _*) => “second is empty” case _ => “default” } The _* binds to any number of elements including none. This … Read more

How to use third party libraries with Scala REPL?

Of course, you can use scala -cp whatever and manually manage your dependencies. But that gets quite tedious, especially if you have multiple dependencies. A more flexible approach is to use sbt to manage your dependencies. Search for the library you want to use on search.maven.org. Algebird for example is available by simply searching for … Read more

Usages of Null / Nothing / Unit in Scala

You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: “The reason Scala has a bottom type is tied to its ability to express variance in … Read more

tech