Search code examples
dartoperatorsvariable-assignment

Using assignment operators in Dart


void main()
{
  var a=10;
  var b=2;
  var toplam=a+=b;
  var fark=a-=b;
  var carpim=a*=b;
  var bolme=a/=b;
  print("$toplam");
  print("$fark");
  print("$carpim");
  print("$bolme");
}

This code gives the following error when splitting: "A value of type 'double' can't be assigned to a variable of type 'int'."


Solution

  • When you do:

    var a=10;
    

    the type of a is inferred from the right-hand-side of the assignment. The right-hand-side is an int literal, so a is inferred to be of type int.

    Later when you try to do:

    var bolme=a/=b;
    

    the a /= b part fails because int.operator / always returns a double, and therefore that result can't be assigned to a which can store only ints.

    If you want a to be able to store doubles, then you must declare it to be a double (or to be a num, the base class for int and double):

    double a = 10;
    

    or

    var a = 10.0;
    

    or

    num a = 10;
    

    Alternatively if your intent is to perform integer division, you should be using int.operator ~/:

    var a = 10;
    var b = 2;
    var bolme = a ~/= b;