简体   繁体   English

等同于特质的单一抽象方法?

[英]Single Abstract Method Equivalent to a Trait?

Consider this trait: 考虑以下特征:

trait Foo {
  def m1(id : Int) : Try[String]
}

And an instance of this: 并举例说明:

  val g : Foo = new Foo {
    override def m1(id: Int): Try[String] = Success("Good job")
  }

Intellij offered a suggestion that this could converted to a Single Abstract Method: Intellij建议将其转换为单一抽象方法:

  val g : Foo = (id: Int) => Success("Good job")

Are these two equivalent and how? 这两个等效吗?

Lets check what the scalac do for: 让我们检查一下scalac作用:

import scala.util.{Success, Try}

trait Foo {
  def m1(id : Int) : Try[String]
}

object MainClass {
  val g : Foo = new Foo {
    override def m1(id: Int): Try[String] = Success("Good job")
  }
}

run: 跑:

$ scalac -print src/main/scala/MainClass.scala

and output: 并输出:

[[syntax trees at end of                   cleanup]] // MainClass.scala
package <empty> {
  abstract trait Foo extends Object {
    def m1(id: Int): scala.util.Try
  };
  object MainClass extends Object {
    private[this] val g: Foo = _;
    <stable> <accessor> def g(): Foo = MainClass.this.g;
    def <init>(): MainClass.type = {
      MainClass.super.<init>();
      MainClass.this.g = {
        new <$anon: Foo>()
      };
      ()
    }
  };
  final class anon$1 extends Object with Foo {
    override def m1(id: Int): scala.util.Try = new scala.util.Success("Good job");
    def <init>(): <$anon: Foo> = {
      anon$1.super.<init>();
      ()
    }
  }
}

And do the same steps for: 并对以下步骤执行相同的步骤:

import scala.util.{Success, Try}

trait Foo {
  def m1(id : Int) : Try[String]
}

object MainClass {

  def main(args: Array[String]): Unit = {
    val g : Foo = (id: Int) => Success("Good job")
  }
}

run: 跑:

$ scalac -print src/main/scala/MainClass.scala

output: 输出:

[[syntax trees at end of                   cleanup]] // MainClass.scala
package <empty> {
  abstract trait Foo extends Object {
    def m1(id: Int): scala.util.Try
  };
  object MainClass extends Object {
    private[this] val g: Foo = _;
    <stable> <accessor> def g(): Foo = MainClass.this.g;
    final <artifact> private[this] def $anonfun$g$1(id: Int): scala.util.Try = new scala.util.Success("Good job");
    def <init>(): MainClass.type = {
      MainClass.super.<init>();
      MainClass.this.g = {
        ((id: Int) => MainClass.this.$anonfun$g$1(id))
      };
      ()
    }
  }
}

As you can see they are not the same for compiler. 如您所见,它们对于编译器而言是不同的。

In the first case, it is an anonymous object in second it is an anonymous function. 在第一种情况下,它是一个匿名对象,其次是一个匿名函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM