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
      Some(childIndex)
    else
      None
  }

Intellij suggests the following variant:

def getRightChildIndex(index : Int) : Option[Int] = {
    val childIndex = (2*index) + 2
    Some(childIndex).filter(isValidIndex)
  }

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.

1 Like

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

1 Like