简体   繁体   中英

Why does this code throw an invalidAssignmentOperator error on the * and + operators?

Why does this code throw an invalidAssignmentOperator error on the * and + operators?

public static Function<Integer, Double> tariff = t -> {
    if (t = 500) {
        t * t;
    } else {
        t + t; 
    }
};

There are several issues with your code:

  1. Equality check needs == : t=500 should be t==500

  2. When you have a complex code as lambda, the return statement is not implicit: so t*t does not return implicitly.

  3. By multiplying/adding two integers you're trying to return a integer value while your expected return type is double , so compilation issues there.

Something like this would work:

  public static Function<Integer, Integer> tariff = t -> {
    if (t == 500) {
      return t * t;
    } else {
      return t + t;
    }
  };

Implicit return would work for something like this:

  public static Function<Integer, Integer> tariff = t -> (t == 500) ? t * t : t + t;

  • Using brackets {} requires the return keyword
  • Primtive type comparison is done with == and not =
  • As you ask for Double as output you need to cast (double) , because int*int > int (same for + ) OR use Function<Integer, Integer>
Function<Integer, Double> tariff = t -> {
    if(t==500) {
        return (double)t*t;
    } else {
        return (double)t+t;
    }
};

To simplify you could do :

Function<Integer, Double> tariff = t -> t==500 ? t*t : t+t;

Your function is throwing an invalidAssignmentOperator because you are not actually assigning t*t or t+t to anything. You can try using t*=t and t+=t so that it will actually assign to t

Your method also is not returning anything and it should. An even better solution to my idea above would be to just return those values:

 public static Function<Integer, Double> tariff = t -> {
    if(t=500) {
        return t*t;
    } else {
        return t+t;
    }
};

Also, be sure to properly space out your code as shown by my code. It makes it much easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM