我们如何为特征创建对象?

How are we creating an object for a trait?

如果 PartialFunction 是一个特征,那么这段代码是如何工作的?我们是在创建特征对象吗?

  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")

阅读有关匿名实例创建的信息。

例如考虑

trait Runnable {
  def run: Unit
}

创建Runnable对象有两种方式

  1. 创建一个扩展 Runnable 的 class Foo 并创建 Foo

    的实例
    class Foo extends Runnable {
     def run: Unit = println("foo")
    }
    
    val a: Runnable = new Foo()
    
  2. 创建一个 Runnable 的匿名实例(您不需要创建一个中间 class(类似于 Foo))。这很方便

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

PartialFunction特征相同。

包括@Tzach Zohar 的评论

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