开发者

Syntax for applying a set of functions to an object

I'm trying to figure the correct syntax in Scala to apply a set of functions to an object. Say I have a class:

class MiTestClass {
   def isValid() : Bool = {...}
   def isGreen() : Bool= {...}
   def isYellow() : Bool = {...}
}

and I create a new object val miTestObj = new MiTestClass now I want to apply a subset of methods to my object like

val conditions:List[MiTestClass => Boolean] = List(_.isGreen, _.isYellow)

and to perform some operation, say for instance to check that all properties hold

val result:Bool  = resultOfApplyingFunctions.foldLeft(true)(and)

What is the syntax for getting such functionality? In H开发者_开发技巧askell you would write something like

map (\f -> f miTestObj) conditions

but I can not get the Scala syntax right


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


conditions.map(f => f(miTestObj))

or

conditions map (_(miTestObj))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜