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?
Use the with Keyword in ScalaThis keyword is usually used when dealing with class compositions with mixins. Mixins are traits that are used to compose a class. This is somewhat similar to a Java class that can implement an interface.
The first thing you inherit from can either be a trait or a class, using the extends keyword. You can define further inherited traits (and only traits) using the with keyword. If a trait inherits from a class you cannot use it like in the above example. That's it regarding the extends and with keywords.
2.2. In Scala, all statements are expressions that return a value. The value of the last statement determines the value of an expression. The if expression is no different — it always returns a value. So, we can assign the result of an if expression to a value.
You can use the isInstanceOf method to test the type of an object: if (x. isInstanceOf[Foo]) { do something ... However, some programmers discourage this approach, and in other cases, it may not be convenient. In these instances, you can handle the different expected types in a match expression.
{
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With