我们如何为特征创建对象



如果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 的类Foo并创建Foo的实例

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

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

PartialFunction特质也是如此。

包括@Tzach·佐哈尔的评论

您正在创建该特性的匿名实现 - 就像在 Java 中创建接口的匿名实现一样。

最新更新