codingsplash
codingsplash

Reputation: 5075

Function not accepting any parameter

I have a function which does not accept any parameters and returns a partial function.

def receive:PartialFunction[Any,Unit]={
case "hello"=>println("Got it 1")
case 123=>println("Got it 2")
case true=>println("Got it 3")
}
receive("hello")

I am unable to understand this function invocation syntax. How is the string being passed to the receive function and how is the case function executing?

However, I am unable to understand the below code as well:

def receive():PartialFunction[Any,Unit]={
case "hello"=>println("Got it 1")
case 123=>println("Got it 2")
case true=>println("Got it 3")
}
val y=receive()
y("hello")

Upvotes: 2

Views: 56

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

  1. An anonymous partial function like { case ... } is short for

    new PartialFunction[Any, Unit] {
      def isDefinedAt(x: Any) = x match {
        case "hello" => true
        case 123 => true
        case true => true
        case _ => false
      }
    
      def apply(x: Any) = x match {
        case "hello" => println("Got it 1")
        case 123 => println("Got it 2")
        case true => println("Got it 3")
      }
    }
    

    ([Any, Unit] comes from the expected type in this case.)

  2. Because receive is not a method with parameters, receive("hello") is short for receive.apply("hello").

Upvotes: 3

L.Lampart
L.Lampart

Reputation: 755

I'll try to explain second part of your question. As you can see there is small difference between two definitions of receive method, one with parenthesis and other without. As it was said in previous answer, call:

val func: Any => Any = ???
func(42)

Is transformed by scala parser to:

func.apply(42)

The same holds true for partial functions (and object of any type having apply method defined). So your invocations are rewrtitten to something like this: First:

val y = receive()
y.apply("hello")

Second:

receive.apply("hello")

Maybe you can see the difference now? You cannot write receive.apply, when receive have (empty, but existing) parenthesis.

Upvotes: 1

Related Questions