Idle pondering from a Scala learner perhaps, but ... in my tinkerings I\'ve written the following:
( n.child.size > 0 ) && ( n.child.filter( ! _.isIns
{
import n.child._
( size > 0 ) && ( filter( ! _.isInstanceOf[Text] ).size == 0 )
}
"with" is, of course, a reserved word in Scala, so let's call it "let", from the similar binding form in Lisp and Haskell. Turns out "let" is just a backwards way of writing function application.
def let[A,B](param:A)(body: A=>B):B = body(param)
let(n.child){list=> ...}
If the bound variable is used only once, you could of course use the anonymous function form, but that defeats the purpose.
class Tap[A](underlying:A){
def tap[B](func: A=>B) = func(underlying)
}
implicit def anyToTap[A](underlying:A)=new Tap(underlying)
n.child.tap{x =>
( x.size > 0 ) &&
( x.filter( ! _.isInstanceOf[Text] ).size == 0 )
}
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.
If you just want to limit the scope of your intermediate variable, you can also just create a block around the predicate:
val n = getNodeByMagic()
val passesTest = {
val child = n.child
child.length == 0 && !child.filter(_.isInstanceOf[Text]).isEmpty
}
// child is not defined outside of the block
you can use match
for that purpose.
n.child match {
case list => ( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 )
}