2

I have the below scenario.

I would like to use a variable inside lambda expression. But this variable will be have a onetime value(final) based on a condition.

  final String constraintsAmount;
  if(constraint.isPresent()) {
       constraintsAmount = constraint.getValue();
  }

After this I start iterating over a list using forEach + lambda expression. Now I have to use this constraintsAmount field inside this iteration.

But it says that "constraintsAmount might not have been initialized".

How can I get around this one.

Note :

  1. I don't want to declare this variable as an instance variable and I certainly don't want to declare and initialize this variable inside the iteration.
  2. Since it is a final I cant initialize it and then reuse it inside the if check. So wanted to check what is the work around.
Bashir
  • 2,057
  • 5
  • 19
  • 44
BigDataLearner
  • 1,388
  • 4
  • 19
  • 40

3 Answers3

5

From a compiler perspective you need an else block:

final String constraintsAmount;
  if(constraint.isPresent()) {
    constraintsAmount = constraint.getValue();
  } else {
    constraintsAmount = ...
  }

Even better the ternary operator:

final String constraintsAmount = constraint.isPresent() ? constraint.getValue() : ...

NOTE: In Java 8 you don't need to declare a variable final to use it in a "closure" (inside lambda stuff).

Or maybe you might need to redesign your code altogether. Hard to tell as I don't have enough information.

Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154
1

Assumimg constraint is an Optional<String> you could do the following:

String constraintsAmount = constraint.orElse(<somedefault>);

Otherwise if you only want to do something if constraint has a value do the following:

constraint.ifPresent(constraintsAmount -> { .... });
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
0

A local variable has to be explicitly initialized before being used.
Your problem is not specific to the final modifier or the use of a lambda expression.

If this condition is true : if(constraint.isPresent()) {, constraintsAmount is initialized. But in the contrary case, it is not initialized. So if you use this variable, the compiler doesn't accept that.

This code illustrates the problem :

  final String constraintsAmount;
  if(constraint.isPresent()) { // initialized
       constraintsAmount = constraint.getValue();
  }
  // if the conditional statement is false, the constraintsAmount var is not initialized

  // So the compiler generates the error 
  // constraintsAmount might not have been initialized

  String lowerCaseString = constraintsAmount.toLowerCase();

Either, value constraintsAmount in an else statement.
Or remove final to give a default value to the variable.

davidxxx
  • 125,838
  • 23
  • 214
  • 215