Scala For Java Developer
Collections
- Scala's
Seq
= Java'sList
, and Scala'sList
= Java'sLinkedList
. - Scala's
Seq
is a trait, equivalent to Java's interface - Java's
List
is an interface, Scala'sList
is an implementation. Scala'sList
is an abstract class that is extended byNil
and::
, which are the concrete implementations ofList
. - Scala's
List
is immutable,LinkedList
is not; Java has no equivalent to immutable collections.
==
Unlike Java, the equals operator (==) checks for true equality, not object reference equality:
scala> val matched = (greeting == "Hello, World")
matched: Boolean = true
companion object
- Scala: companion object
- Java: static
for loop
When you think about
for (int i = 0; i < items.length; i++) {
...
}
for (Item item : items) {
...
}
in scala
for (item <- items) {
}
for (i <- 0 to items.size - 1) {
val item = items(i)
}
for (i <- 0 until items.size) {
val item = items(i)
}
for (i <- items.indices) {
}
Create ArrayList
In Java:
List<Double> list = new ArrayList<>();
In Scala: use ArrayBuffer
val arr = mutable.ArrayBuffer.empty[Double]
Java/Scala Collection Conversion
Problem:
Error:(18, 19) value foreach is not a member of java.util.List[xxx.xxx.xxx.Item]
for (item <- items) {
^
Solution:
add scala.collection.JavaConversions._
import scala.collection.JavaConversions._
...
for (item <- items) {
...
}
Scala Seq to Java List
import scala.collection.JavaConversions._
seqAsJavaList()
break a loop
import scala.util.control.Breaks._
for (...) {
if (...) {
break;
}
}