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?

2 Answers 2

2

Short answer:

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

Let's look at your code:

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

it actually means this:

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

foreach method takes TeamType => Unit as parameter, just like your method forAllTeamTypes.

Sign up to request clarification or add additional context in comments.

Comments

1

You would probably be better off using the built in functions. It would seem like .foreach already has the signature you want.

It will look something like:

TeamType.allTypes.foreach (functionOfYourChoosing)

2 Comments

My TeamType is actually a case object, and not an enum. I should have clarified this
In there you could define a member allTypes that was a List[TeamType] ? Or something. It's hard to judge without a more minimal and complete example :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.