我试图在Scala中找出正确的语法,以将一组函数应用于对象。说我有一堂课:
class MiTestClass {
def isValid() : Bool = {...}
def isGreen() : Bool= {...}
def isYellow() : Bool = {...}
}
然后我想将一个方法的子集应用于对象,例如
val conditions:List[MiTestClass => Boolean] = List(_.isGreen, _.isYellow)
并执行一些操作,例如检查所有属性是否成立
val result:Bool = resultOfApplyingFunctions.foldLeft(true)(and)
获得这种功能的语法是什么?在Haskell中,您将编写类似
map (\f -> f miTestObj) conditions
但我无法正确使用Scala语法
最佳答案
scala> val conditions: List[MiTestClass => Boolean] = List(_.isGreen, _.isYellow)
conditions: List[(MiTestClass) => Boolean] = List(<function1>, <function1>)
scala> val obj = new MiTestClass
obj: MiTestClass = MiTestClass@3dc049d
scala> conditions.forall(_(obj))
res1: Boolean = false
scala> conditions.forall(f => f(obj)) // slightly more verbose way
res2: Boolean = false