Scala case syntax understanding

I'm trying to capture the actors of Scala (Akka), but I just came across some weird bit of “case” that I don't understand:

import akka.actor.{ ActorRef, ActorSystem, Props, Actor, Inbox }
import scala.concurrent.duration._

case object Greet
case class WhoToGreet(who: String)
case class Greeting(message: String)

class Greeter extends Actor {

    var greeting = ""

    def receive = {
        case WhoToGreet(who) => greeting = s"hello, $who"
        case Greet           => sender ! Greeting(greeting) // Send the current greeting back to the sender
    }

}

This bit in particular:

  def receive = {
      case WhoToGreet(who) => greeting = s"hello, $who"
      case Greet           => sender ! Greeting(greeting) // Send the current greeting back to the sender
  }

Now I thought that the case syntax in Scala is as follows:

something match {
    case "val1" => println("value 1")
    case "val2" => println("value 2")
}

If I try to reproduce the usage used in Scala REPL as follows:

def something = {
    case "val1" => println("value 1")
    case "val2" => println("value 2")
}

I get

error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)

What exactly does this mean?

UPDATE: This article is by far the best answer to my question: http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html

+3
source share
1 answer

The syntax of Case in scala has several forms that it can take.

Some examples:

case personToGreet: WhoToGreet => println(personToGreet.who)
case WhoToGreet(who) => println(who)
case WhoToGreet => println("Got to greet someone, not sure who")
case "Bob" => println("Got bob")
case _ => println("Missed all the other cases, catchall hit")

, , , , case .

Case PartialFunction , , , , , .

- :

def something: PartialFunction[Any,Unit] = {
    case "val1" => println('value 1")
    case _ => println("other")
}

.

Akka , , : akka.actor.Actor. typedef Akka:

object Actor {
  type Receive = PartialFunction[Any, Unit]
  ..
}

trait Actor {
  def receive: Actor.Receive 
  ....
} 

def receive: PartialFunction[Any, Unit] = {
}

, Receive .

+3

All Articles