0

I am relatively new to Scala, and just trying to get my head around the use of partially applied functions to solve my problem.

My problem is that in my code I have the following foreach logic in multiple places:

for (teamType <- TeamType.allTypes) {
  findViewById(teamType.layoutID).findViewById(buttonID)
    .setOnClickListener(matchButtonOnClickListener)
}

and again here:

for (teamType <- TeamType.allTypes) refreshTeamStatisticViews(teamType)

Basically, for each teamType in the TeamType case object, I am looking to perform a function that returns Unit

What I was thinking of doing is moving the foreach part into the TeamType case object, and then have that take a function or partially applied function that returns Unit.

So for example, TeamType would contain the following:

def forAllTeamTypes(fun: TeamType => Unit) = for(teamType <- allTypes) fun(teamType) 

and for the second example above, I could change it to

TeamType.forAllTeamTypes(refreshTeamStatisticViews)

However, I am not sure how to apply this for partially applied functions for the more complex first example.

Can someone help me?

4

2 回答 2

2

简短的回答:

TeamType.forAllTeamTypes{ teamType =>
  findViewById(teamType.layoutID).findViewById(buttonID).setOnClickListener(matchButtonOnClickListener)
}

让我们看看你的代码:

for (teamType <- TeamType.allTypes) {
  findViewById(teamType.layoutID).findViewById(buttonID).setOnClickListener(matchButtonOnClickListener)
}

实际上是这个意思:

TeamType.allTypes.foreach{ teamType =>
  findViewById(teamType.layoutID).findViewById(buttonID).setOnClickListener(matchButtonOnClickListener)
}

foreach方法TeamType => Unit作为参数,就像你的方法一样forAllTeamTypes

于 2013-05-27T19:13:55.380 回答
1

使用内置函数可能会更好。似乎.foreach已经有了您想要的签名。

它看起来像:

TeamType.allTypes.foreach (functionOfYourChoosing)
于 2013-05-27T19:05:14.600 回答