Ch.16, Listing 16.4 onward: default getter implementation: shift range of random values by +1


#1

Regarding the Fightable interface damageRoll property’s getter implementation:
To obtain random roll results for e.g. a six-sided dice, shouldn’t it be:


get() = (0 until diceCount).map { Random().nextInt(diceSides) + 1 }.sum()


instead of:


get() = (0 until diceCount).map { Random().nextInt(diceSides + 1) }.sum()

so that the range of values would be 1..6 instead of 0..6?
Cheers!


#2

Correct, this would return 1…6.


#3

You’re right - but you are neglecting to imagine a zero-sided die, something quite common in the world of NyetHack. (Thanks - I’ll add a note to our errata page.)


#4

I knew it!! You guys at BigNerdRanch really are from another dimension (the 0th one, I assume?).
:wink:


#5

Under Intellij 2018.3 and Kotlin 1.3 this line doesn’t compile for me, with the error message : “Cannot create an instance of an abstract class” and Random is underlined in red.
Why ?
EDIT
It seems that :

get() = (0 until diceCount).map { Random.nextInt(diceSides) + 1

compiles nicely.
EDIT 2 So Random seems to have been a concrete class at time when the book was written and could be instanciated by calling a constructor (Random()) but has then become an abstract class, on which it is possible to call some kind of static method (Random.nextInt()).


#6

@glin: Sorry, didn’t check in here for some time now…

Random().nextInt(...) utilizes class Random from the java.util package:
    import java.util.Random

Random.nextInt(...) on the other hand, makes use of Kotlin’s own abstract class Random:
    import kotlin.random.Random

Since Kotlin 1.3, this “multiplatform Random” facility can be used. The Random.Companion object is the default instance that implements this abstract class.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random/index.html