What is a sealed trait?

A sealed trait can be extended only in the same file as its declaration. They are often used to provide an alternative to enums. Since they can be only extended in a single file, the compiler knows every possible subtypes and can reason about it. For instance with the declaration: sealed trait Answer case object … Read more

How do I get around type erasure on Scala? Or, why can’t I get the type parameter of my collections?

This answer uses the Manifest-API, which is deprecated as of Scala 2.10. Please see answers below for more current solutions. Scala was defined with Type Erasure because the Java Virtual Machine (JVM), unlike Java, did not get generics. This means that, at run time, only the class exists, not its type parameters. In the example, … Read more

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking: 1 :: 2 :: Nil // a list list1 ::: list2 // concatenation of two lists list match { case head :: tail => “non-empty” case Nil => “empty” } Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were … Read more

What is the advantage of using abstract classes instead of traits?

I can think of two differences Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are … Read more

What is the difference between self-types and trait subclasses?

It is predominately used for Dependency Injection, such as in the Cake Pattern. There exists a great article covering many different forms of dependency injection in Scala, including the Cake Pattern. If you Google “Cake Pattern and Scala”, you’ll get many links, including presentations and videos. For now, here is a link to another question. … Read more

What do all of Scala’s symbolic operators mean?

I divide the operators, for the purpose of teaching, into four categories: Keywords/reserved symbols Automatically imported methods Common methods Syntactic sugars/composition It is fortunate, then, that most categories are represented in the question: -> // Automatically imported method ||= // Syntactic sugar ++= // Syntactic sugar/composition or common method <= // Common method _._ // … Read more

What is the difference between Scala’s case class and class?

Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments. This functional concept allows us to use a compact initialization syntax (Node(1, Leaf(2), None))) decompose them using pattern matching have equality comparisons implicitly defined In combination with inheritance, case classes are used to mimic algebraic datatypes. … Read more