-1

IDEA shows:

Variable used in lambda expression should be final or effectively final

but isn't String final?

public static boolean isBanned(String promptEn) {
    promptEn = promptEn.toLowerCase(Locale.ENGLISH);
    return BANNED_WORDS.stream().anyMatch(bannedWord -> Pattern.compile("\\b" + bannedWord + "\\b").matcher(promptEn).find());
}

enter image description here

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
djy
  • 737
  • 6
  • 14
  • the variable promptEn isn't final or effectively final, that's the issue. it's not about the datatype, but about the variable – Stultuske May 16 '23 at 07:37
  • 1
    You're assigning a new value to promptEn in line 2. – Sören May 16 '23 at 07:37
  • 2
    A String is immutable. That is not the same as it being `final`. – Ivar May 16 '23 at 07:38
  • "but isn't String final ?" Says who? In what context? – Sweeper May 16 '23 at 07:39
  • 1
    String is declared as a final class, and that means you cannot create a class that extends String. That is a different concept of final than what your IDE is warning you about. `promptEn` cannot be re-assigned. You could make a final variable instead. – matt May 16 '23 at 08:08

1 Answers1

4

String variables have two parts:

  • the value: String is an immutable type, meaning you cannot change it.
  • the variable: when it is final, the value has to be assigned once and cannot be changed later. The value itself may be mutable: when you have a final List<String> list = new LinkedList<>(), you can add and remove elements, but not assign a different list.

Effectively final means that the assigned value is not changed, but the variable is not final (not enforced by language).

Peter Walser
  • 15,208
  • 4
  • 51
  • 78