您可以使一个函数接受两种不同的数据类型吗? [英] Can you make a function accept two different data types?

查看:53
本文介绍了您可以使一个函数接受两种不同的数据类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数应该接受两种不同的数据类型作为输入:

I've got a function that should accept two diffrent data types as input:

vec3 add(vec3 vec){
  this.x += vec.x;
  this.y += vec.y;
  this.z += vec.z;

  return this;
}
vec3 add(num scalar){
  this.x += scalar;
  this.y += scalar;
  this.z += scalar;

  return this;
}

但这会返回错误:

名称"add"已经定义

The name 'add' is already defined

是否有办法在Dart中完成这项工作?我知道类型是可选的,但我想知道是否有办法.

Is there a way to make this work in Dart? I know that types are optional but I would like to know whether there is a way.

推荐答案

Dart不允许函数/方法重载.您可以为方法使用不同的名称,也可以为可选参数或命名可选参数使用不同的名称,以便能够使用具有不同参数集的方法.

Dart doesn't allow function/method overloading. You can either use different names for the methods or optional or named optional parameters to be able to use a method with different sets of parameters.

这篇关于您可以使一个函数接受两种不同的数据类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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