Taran_logo_black
TILBLOGABOUT

Today I learned about...
Scala

Back to all tags

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.

  1. Traits cannot have constructor parameters (you can’t do a new trait)
  2. A class can inherit from multiple traits.
  3. 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

  1. a name, binding any value to that name;
  2. an underscore, matching any value and ignoring it;
  3. a literal, matching the value the literal denotes; or
  4. a constructor-style pattern for a case class.

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:

  1. the ability to omit the val keyword in constructor calls. (A field for each constructor argument)
  2. a nicer toString method for classes
  3. a sensible equals which operates on the field values of an object
  4. 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)