4

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Goudgeld1
  • 342
  • 2
  • 12

3 Answers3

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;
}
kelegorm
  • 935
  • 7
  • 12
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Larry Pickles Sep 08 '15 at 06:58
  • 2
    Question sounds as "Can you make a function accept two different data types?". So I can and I have showed it. – kelegorm Sep 08 '15 at 09:46
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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks for the quick answer, I did'n know it was called method overloading so this is really helpfull :) – Goudgeld1 Sep 06 '15 at 12:39
  • 1
    I wouldn't use optional parameters in any way - either use different names for the two functions (recommended - they do different things) or(/and also) switch on the parameter type `vec3 add(other) => (other is num) ? addScalar(other) : addVector(other);`. The latter can be necessary if an object has to implement two different interfaces that both have an `add` method (but that's usually a sign of overloading too much!) – lrn Sep 08 '15 at 20:28
1

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());
}
Mahmoud Salah Eldin
  • 1,739
  • 16
  • 21