"With" statement equivalent for Scala?

Viewed 2959

Idle pondering from a Scala learner perhaps, but ... in my tinkerings I've written the following:

( n.child.size > 0 ) && ( n.child.filter( ! _.isInstanceOf[Text] ).size == 0 )

('n' is a scala.xml.Node, but that's not important. Nor is the particular logic.)

Calling child() twice isn't so good, so I was about to change it:

val list = n.child
( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 )

But given how much I've come to much appreciate being able to filter() and map() and such without needing to declare intermediate variables, I found this immediately smelly. It's so... so... so Java-ish! :p

Alas, digging through SO and Google and the ScalaDocs (especially Any and AnyRef) and The Book has turned up nothing appropriate. I was hoping perhaps for something like:

n.child{ list => ( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 ) }

or even

n.child.with{ list => ... }

Does something like this exist? Or am I just getting caught up in a variable-less-ness fervour?

6 Answers

Starting Scala 2.13, the standard library now provides a chaining operation method pipe fitting exactly this need:

import scala.util.chaining._

n.child.pipe(list => list.size > 0 && list.filterNot(_.isInstanceOf[Text]).size == 0)

The value of n.child is "piped" to the function of interest.

Related