0

I have following code:

val A = List(...)
val items = A.map(..magic#1..).filter(..magic#2..).map(..magic#3..)
val rndItem = items(Random.nextInt(items.size))

But I want this:

val A = List(...)
val rndItem = A.map(..magic#1..).filter(..magic#2..).map(..magic#3..).getRandom()

Can I do this on scala?

I seen question#1 and question#2

Community
  • 1
  • 1
sheh
  • 1,003
  • 1
  • 9
  • 31
  • I don't think so, unless you will write some helper code (most likely using pimp-my-library pattern), but is this an option for you? – om-nom-nom Jul 30 '14 at 13:54

1 Answers1

2

Sure - use the pimp my library pattern to "add a method" to List:

// We'll use a value class to avoid allocations (in theory anyway)
implicit class RandomList[A](val self: List[A]) extends AnyVal {
  def getRandom(): A = self(Random.nextInt(self.size))
}

See also:

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293