Intellij complains "Replace if with filtered option". What does that mean?


This is my function

def getRightChildIndex(index : Int) : Option[Int] = {
    val childIndex = (2*index) + 2
    if(isValidIndex(childIndex))  // Here intellij asks me to replace if with filtered option


Intellij suggests the following variant:

def getRightChildIndex(index : Int) : Option[Int] = {
    val childIndex = (2*index) + 2

filter takes the optional value and checks it against a condition (i.e. a function returning a boolean), and returns None if it fails (or was already none).

Note that this is a style question, and not really wrong either way. I’d usually only suggest the change, if your value is an Option before the check anyway, in this case I’d say both ways are ok.

You can press Alt-Enter in Intellij when the cursor is over the marked lines, and let it rewrite it automatically or press right-arrow to disable this style inspection if you’d rather stay with the current style.


Some(childIndex).filter(isValidIndex) should be able to replace the whole conditional if desired.