Skip to content

Instantly share code, notes, and snippets.

@oluies
Created July 9, 2010 13:04
Show Gist options
  • Save oluies/469431 to your computer and use it in GitHub Desktop.
Save oluies/469431 to your computer and use it in GitHub Desktop.
trait Randoms {
import scala.util.Random
private val rand = new Random
implicit def seq2RichRandom[K](seq: Seq[K]) = new RichRandom(seq)
protected class RichRandom[K](seq: Seq[K]) {
def random: K = seq((rand.nextFloat * seq.length).toInt)
}
}
@oluies
Copy link
Author

oluies commented Jul 9, 2010

scala> object MyImplicits extends Randoms
defined module MyImplicits

scala> import MyImplicits._
import MyImplicits._

scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> l.random
res0: Int = 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment