Today I learned about...
scala
Back to all tags
Don't forget about closure
Not really a TIL but more of a reminder to myself to not forget about the damn concept of closure and to leverage it in Scala. Just because you have one function to handle sorting, doesn’t mean that function can’t have some helper functions defined within its body.
Abstract classes vs Traits
So Scala is a single inheritance language but allows classes to utilize multiple
traits (these are like interfaces in Java). Traits
and Abstract
classes in
Scala are essentially the same but there are some key differences.
- Traits cannot have constructor parameters (you can’t do a new trait)
- A class can inherit from multiple traits.
- Traits are for behaviors. Abstract classes are for things.
Pattern matching in Scala allows us to do some very nifty things. This is all possible due to the fact that the comparison of objects is not done at the reference level but at the value level.
Refer to the TIL regarding Scala’s case classes😁.
case class Cat(color: String, food: String)
val oswald = Cat("black", "Chips")
object ChipShop {
def willServe(c: Cat): Boolean = {
c match {
case Cat(_, "Chips") => true //don't care about the first argument
case Cat(_, _) => false // don't care about any arguments (this is the default case essentially)
}
}
}
ChipShop.willServe(oswald) // true
A pattern can be one of
- a name, binding any value to that name;
- an underscore, matching any value and ignoring it;
- a literal, matching the value the literal denotes; or
- a constructor-style pattern for a case class.
Scala comparisons
For Scala’s case classes
we get a sensible ==
operator which is different
from Java’s—it delegates to equals rather than comparing values on reference
identity.
Soooo.
new Person("Noel", "Welsh") == new Person("Noel", "Welsh")
// res4: Boolean = true
Scala Case Classes
Scala case classes
are the bread and butter of Scala data types! Learn them ye
fool.
The syntax is as normal but with a case prefix. By using the case
word before
class, Scala provides us some functionality out of the box, including but not
limited to:
- the ability to omit the val keyword in constructor calls. (A field for each constructor argument)
- a nicer toString method for classes
- a sensible equals which operates on the field values of an object
- a copy method that creates a new object with the same field values as the current one
case class Cat(color: String, food: String)
// vs
class Cat(val color: String, val food: String)