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.
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.
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
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
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:
case class Cat(color: String, food: String)
// vs
class Cat(val color: String, val food: String)