unintentionallyborn
unintentionallyborn

Reputation: 13

Confused about returning a when statement

I'm going through Google's Android codelabs building a dice roller app and am a bit confused on how the return type of my function getRandomDiceImage() is type Int, but it seems like the function is returning an ImageView.

I understand getting a random integer and storing it in randomInt, and I get switch statements like in standard C languages. Converting that randomInt to an R.drawable.image is throwing me off though.

private fun getRandomDiceImage(): Int {
    val randomInt = Random().nextInt(6) + 1

    return when (randomInt) {
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }

}

private fun rollDice() {
    diceImage.setImageResource(getRandomDiceImage())
    diceImage2.setImageResource(getRandomDiceImage())
}

Upvotes: 1

Views: 265

Answers (3)

Kartik Shandilya
Kartik Shandilya

Reputation: 3924

Firstly, you are using the function to determine which dice image you'll use based on the random number being generated. Note that when can also be used either as an expression or as a statement.

val drawableResource = when (randomInt) {
    1 -> R.drawable.dice_1
    2 -> R.drawable.dice_2
    3 -> R.drawable.dice_3
    4 -> R.drawable.dice_4
    5 -> R.drawable.dice_5
    else -> R.drawable.dice_6
}

diceImage.setImageResource(drawableResource)

The setImageResource expects an int resId which you are passing through the when expression.

Upvotes: 0

Stanislaw Baranski
Stanislaw Baranski

Reputation: 1418

The type of R.drawable.dice_1 is actually Int, not ImageView. R is a static class, that holds resource ids (of type Int). You can check the real value of the R.drawable.dice_1 by pressing cmd (macOS) or ctrl (Windows) and placing cursor on the dice_1 and you will see, public static final int dice_1 = some_random_number this some_random_number is the id assigned to the drawable (image) resource during the building process.

So your function getRandomDiceImage() : Int indeed return Int type. And the diceImage.setImageResource(getRandomDiceImage()) indeed takes id to the drawable as an argument.

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

getRandomDiceImage() is type Int, but it seems like the function is returning an ImageView.

No, it is returning an images resource identifier, which are @DrawableRes int, such as R.drawable.dice_1 and so on.

diceImage.setImageResource(getRandomDiceImage())

The trick is that setImageResource( expects an int value (that is annotated with @DrawableRes to ensure that it is actually a drawable resource), based on that the ImageView will load the bitmap resource that the drawable identifier refers to.

Upvotes: 2

Related Questions