n+2 } res52: List[Int] = List(3) And it w...">

How to enter anonymous PartialFunction

It works:

scala> List(1, "aa") collect {  case n : Int => n+2 } 
res52: List[Int] = List(3)

And it works great:

scala> var f:PartialFunction[Any, Int] = { case n : Int => n+2 }
f: PartialFunction[Any,Int] = <function1>

scala> var g:PartialFunction[Any, String] = { case n : String => n + " plus two " }
g: PartialFunction[Any,String] = <function1>

scala> List(1, "aa") collect (f orElse g)
res51: List[Any] = List(3, "aa plus two ")

But if I try to do these two together, nope:

scala> List(1, "aa") collect { case n : Int => n+2 } orElse { case n : String => n + " plus two " } 
<console>:8: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: PartialFunction[?,?]
              List(1, "aa") collect { case n : Int => n+2 } orElse { case n : String => n + " plus two " } 

I do not understand why the conclusion does not work, but I can guess. An important question: how to fix it?

+4
source share
1 answer

You need to tell the compiler the argument type of your anonymous PartialFunctions. You can do this directly by annotating their types:

List(1, "aa") collect ({
  { case n : Int => n+2 }: PartialFunction[Any, _]
} orElse {
  { case n : String => n + " plus two " }: PartialFunction[Any, _]
})

Note that in parentheses you must enclose the expression to the right of collect.

If you do not like how verbose, and you do not mind disappointing someone who is trying to understand your code, you can define an identification function PartialFunctionwith input type Any:

def pfa[T](f: PartialFunction[Any, T]): PartialFunction[Any, T] = f

List(1, "aa") collect (
  pfa { case n : Int => n+2 }
  orElse pfa { case n : String => n + " plus two " }
)

, Scala:

def @:[T](f: PartialFunction[Any, T]): PartialFunction[Any, T] = f

scala> @:{case x: Int => x + 3}
res29: PartialFunction[Any,Int] = <function1>
+5

Source: https://habr.com/ru/post/1538885/


All Articles