Search code examples
scalapartialfunction

Scala PartialFunction with isDefinedA and apply not working


I am new in Scala, i was trying PartialFunctions, is this correct way to test functionality, as some tutorials followed this to work, but not working for me?

code:

object MyScalaApp extends App {
def try29{
    val r = new PartialFunction[Int, Int]  
    { 
        def isDefinedAt(q: Int) = q < 0 // Applying isDefinedAt method  
        def apply(q: Int) = 12 * q // Applying apply method 
    }        
    val rr = new PartialFunction[Double, Double]  
    { 
        def isDefinedAt(q: Double) = {q < 0}
        def apply(q: Double) = 12 * q 
    }

    println(r(1))
    println(r(2))        
    println(rr(-1))
    println(rr(-2))
  }
  }
  try29
}

output:

12
24
-12.0
-24.0

Why apply get call when its not matching first condition?
When I write def isDefinedAt(q: Int) = q != 0 it gives println(r(0)) as output 0


Solution

  • According to the ScalaDocs page:

    It is the responsibility of the caller to call isDefinedAt before calling apply...

    Let's try your r() Partial Function in a context where isDefinedAt() is called automatically.

    val r = new PartialFunction[Int, Int] {
      def isDefinedAt(q: Int) = q < 0
      def apply(q: Int) = 12 * q
    }
    List(4,-3,22,-9,0).collect(r)
    //res0: List[Int] = List(-36, -108)
    

    Seems to work as expected.