Scalastyle Boolean expression can be simplified
Asked Answered
B

2

5

Scalastyle (intellij 2016.1 defaults) says this boolean expression can be simplified

val t = Option(true)
val f = Option(false)
if(t.contains(true) && f.contains(false)) {
  println("booop")
}

I can get rid of this by changing the if to:

if(t.contains(true).&&(f.contains(false)))

Or by changing && to &

But not really seeing how this is simplifying it, could anyone explain what's going on?

Update It doesn't appear to be related to if the vals are known at compile time, or them being locally defined. The following code also get's the warning that the expression can be simplfied:

object TestFoo {
  def bar(t: Option[Boolean]) = {
    val f = Option(scala.util.Random.nextBoolean)
    if (t.contains(true) && f.contains(false)) println("booop")
  }
  def main(args: Array[String]) = bar(t = Option(scala.util.Random.nextBoolean))
}

I just don't get how I'm supposed to make that any simpler, is there some strange Option[Boolean] comparing I'm missing out on?

Buggery answered 29/3, 2016 at 12:1 Comment(2)
I was having the same problem. Seems like a bug in ScalaStyle. Changing to infix must just sidestep their regexes for this situation. Using contains seems like the simplest way for this situation.Knightly
There is a newer question with related topic: Simplifying Option[Boolean] expression in ScalaSchismatic
P
4

It seems to suggest you being consistent with the method call usage. Either everything in infix form:

(t contains true) && (f contains false)

Or everything in regular method call form:

t.contains(true).&&(f.contains(false))
Psychographer answered 29/3, 2016 at 15:10 Comment(0)
S
1

With your values, t.contains(true).&&(f.contains(false)) always returns true. So you could simplify it by simply writing true, i.e by just executing the print without an if condition.

Schreck answered 29/3, 2016 at 12:16 Comment(1)
Sorry, the actual code does not use values known at compile time. I've added another example to clarifyBuggery

© 2022 - 2024 — McMap. All rights reserved.