根据类型参数重载方法
我想要一个可以使用或不使用类型参数来调用的方法,并为每个方法返回不同的值。下面是一些明显简化的代码:
object Foo {
def apply() = "Hello"
def apply[T]() = 1
}
使用类型参数调用它很好:
scala> Foo[String]()
res1: Int = 1
但是不使用类型参数调用它不起作用:
scala> Foo()
<console>:9: error: ambiguous reference to overloaded definition,
both method apply in object Foo of type [T]()Int
and method apply in object Foo of type ()java.lang.String
match argument types ()
Foo()
这不是运行时问题,因此添加隐式虚拟参数没有帮助。也没有限制参数 (Foo[Unit]()
)。有没有什么方法可以让编译器明白这一点?
I'd like to have a method that can be called with or without a type parameter, and return a different value for each. Here's some obviously simplified code:
object Foo {
def apply() = "Hello"
def apply[T]() = 1
}
Calling it with a type parameter is fine:
scala> Foo[String]()
res1: Int = 1
But calling it without a type parameter doesn't work:
scala> Foo()
<console>:9: error: ambiguous reference to overloaded definition,
both method apply in object Foo of type [T]()Int
and method apply in object Foo of type ()java.lang.String
match argument types ()
Foo()
It's not a runtime problem, so adding an implicit dummy parameter doesn't help. Nor does having a restricted parameter (Foo[Unit]()
). Is there any way of doing this that isn't ambiguous to the compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上正在重载返回类型。
虽然 Scala 和 Java 通常都不允许您这样做,但在这种情况下却发生了这种情况。
Foo() : String
在这种情况下可以工作,但尽管是否需要对返回类型进行重载,但仍然存在疑问。You are effectively overloading on the return type.
While neither Scala nor Java let you normally let you do so in this case it happens.
Foo() : String
will work in this case but it remains questionable though if overloading on the return type is desirable.