Search code examples
scalamatchcase

How to removal the Nothing type matched in case phase (scala)?


During a function I use the simple code:

 match{
   case Some(one)=>one.copy()
   case Type =>
   ...
   case _ =>
}

There is error, since the Nothing is subtype of every type and Nothing do not have copy function.

AnyOne know how to delete the Nothing and Null Type matching in using match case phase?


Solution

  • The first thing to note is that no instances of Nothing ever exist, and so you will never be in the situation where your match gets a value of Nothing.

    That said, for the general case, the most obvious way is to simply provide cases for those first - cases are tested and executed in order, so adding them before the case the problem occurs at will result in the behavior you want:

    ??? match {
       case null => ???
       case Some(one) => one.copy()
       case Type =>
       ...
       case _ => ???
    }
    

    Obviously, the one of the main points of the Option type is to avoid the need for null checks. If you are ending up with a null in an Option variable, it's probably worth changing your code so that never happens.