# int

## How to generate a small random number in Kotlin

If you need to generate a small random number in Kotlin, I find that this approach works:

`val r = (1..10).shuffled().first()`

That code generates a single random number in the range from 1 to 10 (including 1 on the low end and 10 on the high end).

You can use the technique to simulate the rolling of a dice (die):

`val r = (1..6).shuffled().first()`

Or simulate flipping a coin (0=heads, 1=tails, or vice versa):

```val r = (1..2).shuffled().first()
```

This also works for the coin flip simulation:

## How to get the current year as an integer in Scala

Scala FAQ: How do I get the current year as an integer (`Int` value) in Scala?

Solution: Use the Java 8 `Year` or `LocalDate` classes, or the older old Java `Calendar` class. The solutions are shown below.

## How to create a Java or Scala date from a Long value

Scala FAQ: How do I created a Scala `Date` from a `Long` value? When I give the Java Date class constructor a `Long` value it returns a date from 1970.

Solution: You need to multiply the `Long` value by 1000, and also make sure you pass a `Long` value into the `Date` constructor. The Scala REPL shows how this works:

## How to handle very large numbers in Scala (BigInt, BigDecimal)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.6, “Handling Very Large Numbers in Scala.”

## Problem

You’re writing a Scala application and need to use very large integer or decimal numbers.

## Solution

Use the Scala `BigInt` and `BigDecimal` classes. You can create a `BigInt`:

## Scala: How to parse a number from a String

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.1, “Parsing a Number from a String.”

## Problem

You want to convert a `String` to one of Scala’s numeric types (`Byte`, `Double`, `Int`, `Float`, `Long`, `Short`).

## How to populate a Java int array with a range of values

I just learned an easy way to populate/initialize a Java `int` array with data, such as a range of numbers. The key is to use the `rangeClosed` method on the Java 8 `IntStream` class. Here’s an example using the Scala REPL:

```scala> val n = java.util.stream.IntStream.rangeClosed(0, 10).toArray()
n: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)```

I show that in Scala to show the output, and here’s what it looks like with Java: