Scala:方法apply在尝试重载case类apply方法时定义了两次

时间:2017-04-12 09:18:28

标签: scala apply

我试图重载案例类的apply方法:

case class Percentage(value: Double)

object Percentage {
  def apply(value: Double): Percentage = {
    if (value < -1) new Percentage(-1.0)
    else if (value > 1) new Percentage(1.0)
    else new Percentage(value)
  }
}

但是我收到以下错误:

method apply is defined twice conflicting symbols both originated in file

为什么我会收到此错误?

1 个答案:

答案 0 :(得分:5)

定义案例类时,编译器实际上会生成一个apply方法。如果您跳过在随播对象中定义apply,则这是已编译的代码:

$ javap Percentage$.class
Compiled from "SparkHangTest.scala"
public final class org.kp.funspark.Percentage$ implements scala.Serializable {
  public static final org.kp.funspark.Percentage$ MODULE$;
  public static {};
  public org.kp.funspark.Percentage apply(double);
  public scala.Option<java.lang.Object> unapply(org.kp.funspark.Percentage);
}

您收到错误是因为您使用与生成的方法相同的参数和返回类型定义了apply。因此,您基本上尝试使用带有完全相同参数且具有相同返回类型的apply来覆盖apply方法。

例如,如果你使用apply的另一个参数,则没有冲突:

case class Percentage(value: Double)

object Percentage {
  def apply(value: Int): Percentage = {
    if (value < -1) Percentage(-1.0)
    else if (value > 1) Percentage(1.0)
    else Percentage(value)
  }
}

编译代码:

$ javap Percentage$.class
Compiled from "SparkHangTest.scala"
public final class org.kp.funspark.Percentage$ implements scala.Serializable {
  public static final org.kp.funspark.Percentage$ MODULE$;
  public static {};
  public org.kp.funspark.Percentage apply(int); // This is the new apply
  public org.kp.funspark.Percentage apply(double);
  public scala.Option<java.lang.Object> unapply(org.kp.funspark.Percentage);
}