Start Creating
Data For AI

1/2 2/2

Want to talk to our sales team instead?

By logging in, you agree to our terms of service and privacy policy

Tech Notes

Class Methods on Null in Scala

blog-details-banner

blog-details-userKoert Kuipers

blog-details-eye-slashAug 31, 2022

blog-details-banner

i recently was debugging a simple refactoring of some scala code that led to a surprise NullPointerException. we generally avoid using null and prefer to use Option[T] where None replaces (null: T), and we assume in our code base that no null will be passed in. in this case it seemed a null had sneaked in there anyhow, and before the refactoring we handled it correctly while after the refactoring we were no longer, leading to the NullPointerException. while digging it in seemed like we were magically able to handle methods on null instances of a class! so this is a blog post about some funky edge case in scala that made this possible.

lets assume we have a class for a person and we want to check if the person is null. you could try this:

case class Person(first: String, last: String) { 
  def isNull: Boolean = this == null 
}

but of course this method isNull doesn’t do anything useful because you cannot call a method on null:

scala> Person("koert", "kuipers").isNull 
val res0: Boolean = false 

scala> (null: Person).isNull 
java.lang.NullPointerException ... 59 elided

so what i realized by accident while debugging is that there is a way to make this work using scala’s implicit class:

case class Person(first: String, last: String) 
implicit class RichPerson(val person: Person) extends AnyVal { 
  def isNull: Boolean = person == null 
}

now the result is:

scala> Person("koert", "kuipers").isNull 
val res0: Boolean = false 

scala> (null: Person).isNull 
val res1: Boolean = true

i cannot recommend relying on this! however i thought it was fun to share…

Mirror Link – https://technotes.tresata.ai/method-on-null