我正在尝试在Scala中找出正确的语法,将一组函数应用于对象。说我上课了:
class MiTestClass {
def isValid() : Bool = {...}
def isGreen() : Bool= {...}
def isYellow() : Bool = {...}
}
我创建了一个新对象val miTestObj = new MiTestClass
现在我想将一个方法的子集应用到我的对象,如
val conditions:List[MiTestClass => Boolean] = List(_.isGreen, _.isYellow)
并执行某些操作,比如说检查所有属性是否保持
val result:Bool = resultOfApplyingFunctions.foldLeft(true)(and)
获取此类功能的语法是什么?在Haskell中你会写类似
的东西map (\f -> f miTestObj) conditions
但我无法正确使用Scala语法
答案 0 :(得分:6)
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
答案 1 :(得分:5)
conditions.map(f => f(miTestObj))
或
conditions map (_(miTestObj))