[Scala] Add your own method for primitive class

mj park
2 min readJan 9, 2021

--

Problem

When writing code in Scala, we often want to replicate something with the primitive classes. For example, if many variables were written in a type of Option[String], using pattern matching to get its value or default one is a good way of getting what’s within Some.

object StringUtils {
def unpack(packed: Option[String]): String = {
packed match {
case Some(value) => value
case None => "default"
}
}
}

val foo: Option[String] = Some("Hello, World!")
val bar: Option[String] = None
StringUtils.unpack(foo) // returns "Hello, World!"
StringUtils.unpack(bar) // returns "default"

When writing code, I try to force myself for DRY (Don’t Repeat Yourself). So, can I do something better than repeating StringUtils.unpack() every time I need to unpack Option[String] ?

Solution

Fortunately, there is a way to handle this problem. We can define an implicit class with the behaviors we want to have as a default.

implicit class StringUtil(os: Option[String]) {
def unpack(): String = {
os match {
case Some(value) => value
case None => "default"
}
}
}

However, if you declare the above code in the top-level, it will give you an error “An implicit class must be defined in a scope where method definitions are allowed (not at the top level)”.

You must define your implicit class inside one of these, and I want to show you my preferred way — Inside Object

  1. Class
  2. Object
  3. Package Object

Inside Object

  • Define an implicit class inside Object
package com.scala.cookbook object StringUtils {
implicit class StringImprovement(os: Option[String]) {
def unpack(): String = {
os match {
case Some(value) => value
case None => "default"
}
}
}
}
  • Import the object from another package and use it wisely :)
import com.scala.cookbook.StringUtils._
val foo = Some("Hello, World!")
foo.unpack() // returns "Hello, World!"

val bar = None
bar.unpack() // returns "default"

Again, this trick becomes really handy when you have many duplicate operations on a specific type of variable. My example uses Option[String] because this type of variable is commonly used in my project, but this trick can be extended to any case. Hope this post helps you, and thanks for reading my post.

Happy programming :)

--

--

mj park
mj park

Written by mj park

Software Engineer | Scala | Functional Programming

No responses yet