directly applying lift function not give expected function

Viewed 101

Below are the two partial function that are expected to perform sme tasks but defined in diffrent ways.

val pf1 : PartialFunction[String, String] = { 
  case s : String if (s != null) =>  s.toUpperCase()
}
//> pf1  : PartialFunction[String,String] = <function1>

val lift1 = pf1.lift
//> lift1  : String => Option[String] = <function1>

val d1 = lift1(null)
//> d1  : Option[String] = None

val d2 = lift1("hello world")
//> d2  : Option[String] = Some(hello world)

val pf2 = PartialFunction[String, String] { 
  case s : String if(s != null) =>  s.toUpperCase()
}
//> pf2  : PartialFunction[String,String] = <function1>

val lift2 = pf2.lift
//> lift2  : String => Option[String] = <function1>

val d3 = lift2(null)
//> scala.MatchError: null

val d4 = lift2("hii")
//> d4  : Option[String] = Some(hii)

Why passing null to lift2 gives MatchError, when the definition of both lift1 and lift2 is same?

2 Answers
Related