filter and report multiple predicates

后端 未结 3 1239
长发绾君心
长发绾君心 2020-12-21 20:54

This is a kind of cosmetic Scala question. A list with objects needs to be filtered on the objects\' attributes. I need to report if the first check on the attribute results

3条回答
  •  暖寄归人
    2020-12-21 21:47

    The following code is a slight modification from this SO answer from Rex Kerr.

    implicit class KestrelPattern[A](private val repr: A) extends AnyVal {
      def tee[B](f: A => B) = { f(repr); repr } // B is thrown away (Unit)
    }
    

    He called it tap. I chose tee because of the similarity to the unix tee command.

    Usage:

    scala> List[Int](3,5,7).tee{x => if (x.isEmpty) println("ERROR")}.sum
    res42: Int = 15
    
    scala> List[Int]().tee{x => if (x.isEmpty) println("ERROR")}.sum
    ERROR
    res43: Int = 0
    

提交回复
热议问题