简体   繁体   English

为什么此代码为什么在*和+运算符上引发invalidAssignmentOperator错误?

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

Why does this code throw an invalidAssignmentOperator error on the * and + operators? 为什么此代码为什么在*和+运算符上引发invalidAssignmentOperator错误?

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 平等检查需求==t=500应该是t==500

  2. When you have a complex code as lambda, the return statement is not implicit: so t*t does not return implicitly. 当您有一个复杂的代码作为lambda时, return语句不是隐式的:因此t*t不会隐式返回。

  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. 通过将两个整数相乘/相加,您试图在期望的返回类型为double返回一个integer数值,因此编译在那里出现。

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 使用方括号{}需要return关键字
  • 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> 当您要求将Double作为输出时,您需要强制转换(double) ,因为int*int > int (与+相同) 使用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. 您的函数抛出了invalidAssignmentOperator,因为您实际上并未将t*tt+t分配给任何东西。 You can try using t*=t and t+=t so that it will actually assign to t 您可以尝试使用t*=tt+=t以便将其实际分配给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. 它使阅读变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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