也许是从Scala学习者那里闲聊,但是...在我的修补中我写了以下内容:
( n.child.size > 0 ) && ( n.child.filter( ! _.isInstanceOf[Text] ).size == 0 )
Run Code Online (Sandbox Code Playgroud)
('n'是一个scala.xml.Node,但这并不重要.也不是特定的逻辑.)
两次打电话给孩子()并不是那么好,所以我打算改变它:
val list = n.child
( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 )
Run Code Online (Sandbox Code Playgroud)
但考虑到我已经非常欣赏能够过滤()和map()等而不需要声明中间变量,我立即发现这很臭.它就是......所以......所以Java-ish!:p
唉,通过搜索SO和谷歌以及ScalaDocs(特别是Any和AnyRef)和The Book已经找不到合适的东西.我希望也许是这样的:
n.child{ list => ( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 ) }
Run Code Online (Sandbox Code Playgroud)
甚至
n.child.with{ list => ... }
Run Code Online (Sandbox Code Playgroud)
这样的事情存在吗?或者我只是陷入了一种不变的热情?
Ken*_*oom 21
{
import n.child._
( size > 0 ) && ( filter( ! _.isInstanceOf[Text] ).size == 0 )
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ith 18
"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=> ...}
Run Code Online (Sandbox Code Playgroud)
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 )
}
Run Code Online (Sandbox Code Playgroud)