本文介绍了Scala:在具有隐式、柯里化和默认值的重载方法中的偏好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下简单的代码无法编译:

The following simple piece of code fails to compile:

object O {
  def apply(s:String, o:Int=5)(implicit i:String) = {
    println("am first");
    s
  }

  def apply(s:String)(o:Boolean*) = {
    println("am second");
    o
  }
}

object Main extends App {
  implicit val myS = "foo"
  O("test")
}

错误是

error: missing arguments for method apply in object O;
follow this method with `_' if you want to treat it as a partially applied function
  O("test")
   ^
one error found

这似乎是因为编译器更喜欢第二个apply.但这是为什么呢?特别是考虑到申请第一个apply的条件是否满足?如果我删除第二个 apply 这段代码编译得很好.

This appears to be because the compiler prefers the second apply. But why is this? Especially considering that the conditions for applying the first apply are satisfied? If I delete the second apply the piece of code compiles fine.

有什么方法可以引导"编译器正确编译它?还是我被迫创建两个不同的方法名称?

Are there any way to "guide" the compiler towards compiling this correctly? Or am I forced to create two different method names?

推荐答案

您说得对,Scala 编译器可以变得更智能.问题是没有人想为此提出新的规范.会很复杂.

You're right that it is possible for the Scala compiler to be smarter. The problem is that noone has wanted to come up with the new specification for this. It'll be very complicated.

有很多方法可以绕过这个限制.

There are ways to get around this limitation.

def apply(s: String, i: Option[Int] = None) = {
  i match {
    case Some(n) => // call the 1st
    case None => // call the 2nd
 }

}

那么:

apply("test", Some(5)) => ... // if we want the first
apply("test") => ... // if we want the second

2.对两个函数使用重载但参数名称不同:

def apply(apple: String, o: Int = 5)(implicit i: String)
def apply(banana: String)(o: Boolean*)

那么:

apply(apple = "test") // if we want the first
apply(banana = "test") // if we want the second

这篇关于Scala:在具有隐式、柯里化和默认值的重载方法中的偏好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:16