我可以从 Scala 中的重载方法中获取函数吗? [英] can I get a function from an overloaded method in scala?

查看:39
本文介绍了我可以从 Scala 中的重载方法中获取函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了两个具有相同名称和返回值但参数不同的方法:

Let's say that I have two methods defined with the same name and return, but different params:

def overload(x: Int) = x.toString
def overload(s: String) = s

现在我想将其中一个转换为函数.如果该方法没有重载,我会这样做:

Now I want to convert one of them to a function. If the method weren't overloaded, I would do this:

val f = overload _

但既然是这样,编译器就会正确地抱怨引用不明确.除了重命名其中一个方法之外,还有什么方法可以使一个或另一个重载方法的函数成为一个函数?

But since it is, the compiler rightly complains about an ambiguous reference. Is there any way to make a function of one or the other of the overload methods other than to rename one of them?

谢谢!

约翰

推荐答案

当你直接调用它时,编译器知道要调用哪个 overload 的方式是通过知道它所应用的参数的类型.overload someInt 只能指overload(x: Int),所以没有歧义.

The way the compiler knows which overload to call when you call it directly is by knowing the type of the argument it's applied to. overload someInt can only be referring to overload(x: Int), so there's no ambiguity.

当你用它创建一个函数时,你还没有提供参数(还没有),所以编译器不知道你想要你的函数是什么类型,所以它不知道哪个重载你指的是.

When you make a function from it, you haven't supplied an argument (yet), so the compiler has no idea what type you want your function to be, so it doesn't know which overload you're referring to.

解决这个问题的简单方法是明确地告诉它类型:

The easy way to fix that is to explicitly tell it the type:

val f : Int => String = overload _

或:

val f = (x : Int => overload x)

或:

val f = overload (_ : Int)

(注意:我还没有测试过这些,但它们的一些变化应该可以工作)

(note: I haven't tested these yet, but some variation on them should work)

这篇关于我可以从 Scala 中的重载方法中获取函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆