Can you make a function accept two different data types?

ぃ、小莉子 提交于 2020-11-29 09:06:06

问题


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

but this returns an error:

The name 'add' is already defined

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.


回答1:


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.




回答2:


Unlikely C++ or Java, in Dart you can't do method overloading. But you can use named optional parameters like bellow:

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



回答3:


Try this Way:

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


来源:https://stackoverflow.com/questions/32423409/can-you-make-a-function-accept-two-different-data-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!