0
\$\begingroup\$

I'm having trouble to implement the following requirement in a functional way in scala. Given a predefined number of boolean flags, I want to build up a collection of numbers. For each (true) flag, a hardcoded number should be included in the collection.

This is the unsatifying solution I have so far:

 def createCodeArray(flagA:Boolean, flagB:Boolean, flagC:Boolean): Seq[Int] = {
 val codes = ListBuffer.empty[Int]
 if(flagA) codes += 2
 if(flagB) codes += 7
 if(flagC) codes += 12
 return codes
 }

I'm trying to achieve to same with pattern matching, but I don't want to list all the possible combinations. Also, I'd like to avoid mutable data-structures.

Any suggestion on how to write this in a functional way is much appreciated

asked May 19, 2017 at 12:45
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Could you tell us more about where these flags come from, how this method is called, and how the resulting list will be used? \$\endgroup\$ Commented May 19, 2017 at 12:49
  • \$\begingroup\$ @200_success this should not matter for this question, the method's functionality and signature should just remain as it is \$\endgroup\$ Commented May 19, 2017 at 18:43

1 Answer 1

1
\$\begingroup\$

You could use tuples to pair your flags with an Int. Throw those into a Seq and then perform a filter and then a map on that Seq. Here is how that would look:

def f(a: Boolean, b: Boolean, c: Boolean): Seq[Int] = {
 val xs = Seq((a, 2), (b, 7), (c, 12))
 xs.filter(t => t._1).map(t => t._2) 
}

Note that in Scala you don't need to use a return statement as long as the last bit of code in your function returns a new value.

answered May 19, 2017 at 18:26
\$\endgroup\$
2
  • \$\begingroup\$ @thanks, I'm aware that the return statement is not needed, still I'd like to use it to make the code more "speaking" \$\endgroup\$ Commented May 19, 2017 at 18:44
  • 1
    \$\begingroup\$ @Raphael, sure with return statement it is more "speaking", but it is against Scala coding style. A good explanation is given here. \$\endgroup\$ Commented May 20, 2017 at 6:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.