Dart中的函数重载 [英] Function overloading in Dart

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

问题描述

以下代码:

class Tools {
  static int roll(int min, int max) {
    // IMPLEMENTATION
  }

  static int roll(List<int> pair) {
    // IMPLEMENTATION
  }
}

提供a 名称 roll已定义错误在第二个 roll 函数上。

renders a The name 'roll' is already defined error on the second roll function.

为什么?由于函数的参数是不同的,因此多态性不适用吗?

How come? Since the parameters of the functions are distinct, shouldn't polymorphism apply?

编辑。为了更好地反映主题,更正了标题。

Edit. Corrected title in order to better reflect the subject.

推荐答案

您的代码演示的是函数重载,与多态无关。

What your code demonstrates is function overloading and not related to polymorphism.

Dart完全不支持函数重载。

您可以使用其他函数方法的名称或可选的已命名或未命名的参数

You can either use different names for the methods or optional named or unnamed parameters

// optional unnamed
void foo(int a, [String b]);
...
foo(5);
foo(5, 'bar');

// optional named
void foo(int a, {String b});
...
foo(5);
foo(5, b :'bar');

可选参数也可以具有默认值。
不能一起使用可选的已命名和未命名参数(单个函数只能使用一个或另一个)

Optional parameters can also have default values. Optional named and unnamed parameters can not be used toghether (only one or the other for a single function)

多态和静态方法:

只能在没有定义类名作为前缀的情况下从定义它们的类内部访问静态方法。从子类中调用时,需要将超类的名称用作前缀。

Static methods can only be accessed without the class name as prefix from inside the class where they are defined. When called from subclasses, the name of the superclass needs to be used as prefix.

这篇关于Dart中的函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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