为什么方法重载在另一个方法中不起作用? [英] Why method overloading does not work inside another method?

查看:42
本文介绍了为什么方法重载在另一个方法中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类或对象主体中,这是有效的:

In the class or object body, this works:

def a(s:String) {}
def a(s:Int) {}

但是如果将它放在另一个方法中,则不会编译:

But if it is placed inside another method, it does not compile:

def something() {
  def a(s:String) {}
  def a(s:Int) {}
}

为什么会这样?

推荐答案

请注意,您可以通过创建对象来获得相同的结果:

Note that you can achieve the same result by creating an object:

def something() {
  object A {
    def a(s:String) {}
    def a(i: Int) {}
  }
  import A._
  a("asd")
  a(2)
}

在您的示例中,您定义了本地函数.在我的示例中,我声明了方法.对象、类和特征允许静态重载.

In your example, you define local functions. In my example, I'm declaring methods. Static overloading is allowed for objects, classes and traits.

我不知道为什么局部函数不允许使用它,但我的猜测是重载是一个可能的错误来源,并且在代码块中可能不是很有用(大概您可以在该块范围内使用不同的名称).我认为它在类中是允许的,因为它在 Java 中是允许的.

I don't know why it's not allowed for local functions but my guess is that overloading is a possible source of error and is probably not very useful inside a code block (where presumably you can use different names for in that block scope). I assume it's allowed in classes because it's allowed in Java.

这篇关于为什么方法重载在另一个方法中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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