Search code examples
scalapartialfunction

How are we creating an object for a trait?


If PartialFunction is a trait, then how does this code work? Are we creating an object of the trait?

  def x=new PartialFunction[Any, Unit] {
    def isDefinedAt(x: Any) = x match {
      case "hello" => true
      case "world" => true
      case _=> false
    }
    def apply(x: Any) = x match {
      case "hello" => println("Message received hello")
      case "world"=> println("Message received world")
    }
  }

  x("hello")
  if (x.isDefinedAt("bye") ){ x("bye")}
  x("bye")

Solution

  • Read about anonymous instance creation.

    For example consider

    trait Runnable {
      def run: Unit
    }
    

    There are two ways to create an object of Runnable

    1. Create a class Foo which extends Runnable and create instance of Foo

      class Foo extends Runnable {
       def run: Unit = println("foo")
      }
      
      val a: Runnable = new Foo()
      
    2. Create an anonymous instance of Runnable (you need not create a intermediate class (something like Foo)). This quite handy

      val a: Runnable = new Runnable {
         override def run: Unit = println("foo")
      } //no need to create an intermediate class.
      

    Its the same case with PartialFunction trait.

    Including the comment of @Tzach Zohar

    You are creating an anonymous implementation of the trait - just like creating an anonymous implementation of an interface in Java. – Tzach Zohar