Wednesday, March 3, 2010

Functions using case statements

A further tip regarding using case statements to construct functions. If a case statement is assigned to a Function it will construct a Function object not a PartialFunction.

I suppose the question is why do you care about this since PartialFunction is a Function. The fact is that a PartialFunction is a Function1. But using a case statement you can construct a Function4 very easily.
  1. scala> def run(f : Function1[Any,Unit]) = println(f.isInstanceOf[PartialFunction[_,_]])
  2. run: (f: (Any) => Unit)Unit
  3. /*
  4. since run expects a Function calling run as shown here will make a 
  5. Function object not a PartialFunction Object
  6. */
  7. scala> run({case f => ()}) 
  8. false
  9. scala> def pf(f : PartialFunction[Any,Unit]) = println(f.isInstanceOf[PartialFunction[_,_]]) 
  10. pf: (f: PartialFunction[Any,Unit])Unit
  11. // Now a PartialFunction will be created
  12. scala> pf({case f => ()})                                                                         
  13. true
  14. scala> def run(f : Function2[Int,String,Unit]) = f(1,"2")                                     
  15. run: (f: (IntString) => Unit)Unit
  16. /*
  17. This demonstrates why it is important that a case creates a Function
  18. when assigned to a Function. PartialFunctions are Function1 objects
  19. but the following statement is creating a Function2 object.
  20. */
  21. scala> run({                 
  22.      | case (1,b) => println(b)
  23.      | case (a,b) => println(a,b)
  24.      | })
  25. 2

No comments:

Post a Comment

Post a Comment