Jose Cabrera Zuniga
Jose Cabrera Zuniga

Reputation: 2625

Printing from logical expressions in Scala

In Scala I have an expression like:

 prods <- Products.getAll(pr => (pr.stockOn >= from &&
                                 !(outOfDate(pr.id))
                                )
                         )

Is it possible to have a println command in the expression:

(pr.stockOn >= from && !(outOfDate(pr.id)) )

Something like:

 (pr.stockOn >= from && !(outOfDate(pr.id)) && (println(outOfDate(pr.id)))

Thx

Upvotes: 0

Views: 47

Answers (2)

som-snytt
som-snytt

Reputation: 39577

Some people like

pr.stockOn >= from && !outOfDate(pr.id) && { println(outOfDate(pr.id)) ; true }

In 2.13, there is

import scala.util.chaining._

outOfDate(pr.id).tap(println).pipe(!_)

which has the benefit of being weirdly cryptic.

Upvotes: 3

Tim
Tim

Reputation: 27356

Yes, you can have multiple lines of code in the body of the function. I would write it like this:

prods <- Products.getAll{pr =>
  val ood = outOfDate(pr.id)

  println(ood)

  pr.stockOn >= from && !ood
}

The last value in the block is the result of the block.

Upvotes: 1

Related Questions