你能让一个函数接受两种不同的数据类型吗?

Can you make a function accept two different data types?

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

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;
}

但这returns是一个错误:

The name 'add' is already defined

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

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

不像 C++ 或 Java,在 Dart 中你不能进行方法重载。但是您可以使用如下命名的可选参数:

vec3 add({num scalar, vec3 vec}) {
  if (vec3 != null) {
    this.x += vec.x;
    this.y += vec.y;
    this.z += vec.z;
  } else if (scalar != null) {
    this.x += scalar;
    this.y += scalar;
    this.z += scalar;
  }
  return this;
}

试试这个方法:

class TypeA {
  int a = 0;
}

class TypeB {
  int b = 1;
}

class TypeC {
  int c = 2;
}

func(var multiType) {
  if (multiType is TypeA) {
    var v = multiType;
    print(v.a);
  } else if (multiType is TypeB) {
    var v = multiType;
    print(v.b);
  } else if (multiType is TypeC) {
    var v = multiType;
    print(v.c);
  }
}

void main() {
  //Send Any Type (TypeA, TypeB, TypeC)
  func(TypeC());
}