Scala Random

A random number generator will generate a number that cannot be predicted.

Although, it is impossible to generatetruerandom number on a computer.

Please take a look at line 3 with theimportstatement. This tells the compiler that, to be able to compile this code, it will need to fetch this other component. In most Scala code you are going to see in your professional life, there will beimportstatements at the beginning of the files. But, do not worry, those are usually added automatically by the development environment (IDE) so you don't have to care for it quite yet.

You recognize thenewfrom the SKB aboutclass. It tells us thatscala.util.Randomis aclassthat needs to be instantiated before able to use it.

Now we have a random generator, what can we do with it? You can generate a lot of different types, here we are only focusing onIntto simplify things but you can take a look atscala.util.Random documentationto see what else is available.

Try running the code several times, do you see that the number generated are different each time?

However, the number generated by the generator started with a seed always generate the same series of number. This is because there are no true random in a computer. A random generator is a function that given a number generate a new number. The starting number is theseed. If you are playing procedurally generated games, such as Minecraft for instance, this is what theseedis for, it initializes the random generator.

One interesting part of this SKB is therandomIntmethod. Did you figure out what was the missing part ? If not, here is the solution:

rand.nextInt(max - min) + min

The first part (rand.nextInt(max - min)) will return an Integer between0andmax - minbut we want something betweenminandmax. We need to addmin. That way, we generate a number between0 + minandmax - min + min, which resolve tomintomax.

There is a little brain candy at the end of the code, did you notice it ?for. This is called afor-comprehension. We are going to go more into details about it in up-coming SKBs.

An other brain candy is therange. In Scala, you can describe a range of number in different ways:

  • 0 to 2will generate the numbers0, 1, 2
  • 0 until 2which will generate the numbers0, 1
  • 0 until 10 by 3which will generate the numbers0, 3, 6, 9

Reveal more information and clues
Load Exercise