1
votes

Having issues with trying to get my case match to work as expected. The outcome I am looking for is as follows:

case 1 OR 2 => randomly select one reference

case any other number above 2 => randomly select (number - 2) reference

case None => throw exception

Im having problems implementing this. so far I have:

 val randomList: List = actualList.size match {
      case 1 => scala.util.Random.shuffle(actualList).take(1)
      case x? => scala.util.Random.shuffle(actualList).take(2)
      case None => throw new IllegalStateException("references have not been generated successfully.")
    }

I get an error message with the 'None' stating the pattern type is incompatible with expected type Int.

If there is a better way to implement this, please do share.

Any help would be much appreciated.

Thanks

2
what does "case None" represent in your description? actualList.size produces Int so it would never be None. Did you mean 0? - Alvaro Carrasco
@AlvaroCarrasco Hi yes, that's what i meant. it literally just went over my head that the list was an Int >.< Thanks - user610

2 Answers

2
votes

You can use |, guard and _ to achieve this

  val randomList: List = actualList.size match {
      case 0 => throw new IllegalStateException("references have not been generated successfully.")
      case 1 | 2 => scala.util.Random.shuffle(actualList).take(1)
      case _ => scala.util.Random.shuffle(actualList).take(2)
    }
2
votes

I think you can shuffle right away to simplify each expression in case clauses:

  val actualList = List(1, 2, 3)
  val shuffled = Random.shuffle(actualList)

  shuffled.size match {
    case 0 => throw new RuntimeException()
    case 1 | 2 => shuffled.take(1)
    case _ => shuffled.take(2)
  }