问题
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