“With” statement equivalent for Scala?

前端 未结 6 881
野的像风
野的像风 2021-02-13 10:31

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

( n.child.size > 0 ) && ( n.child.filter( ! _.isIns         


        
相关标签:
6条回答
  • 2021-02-13 10:38
    {
        import n.child._
        ( size > 0 ) && ( filter( ! _.isInstanceOf[Text] ).size == 0 )
    }
    
    0 讨论(0)
  • 2021-02-13 10:39

    "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.

    0 讨论(0)
  • 2021-02-13 10:40
    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 )
    }
    
    0 讨论(0)
  • 2021-02-13 10:46

    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.

    0 讨论(0)
  • 2021-02-13 10:58

    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
    
    0 讨论(0)
  • 2021-02-13 10:58

    you can use match for that purpose.

    n.child match {
    case list => ( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 )
    }
    
    0 讨论(0)
提交回复
热议问题