Why can't I get a specific value from a list in kotlin?

Viewed 36

I'm trying to make a simple card game to get more used to classes in Kotlin, but something Is wrong, here's the code:

class Cards(val cardName: String = "", cardValue: Int = 0, amountDeck: Int = 4) {}

public var allCards = listOf<Cards>(
    Cards("One", 1),
    Cards("Two", 2),
    Cards("Three", 3),
    Cards("Four", 4),
    Cards("Five", 5),
    Cards("Six", 6),
    Cards("Seven", 7),
    Cards("Eight", 8),
    Cards("Nine", 9),
    Cards("Ten", 10),
    Cards("Eleven", 11),
    Cards("Twelve", 12),
    Cards("Ace", 10),
    Cards("Queen", 10),
    Cards("Jack", 10),
    Cards("King", 10)

)

fun drawCard(randomValue: Int) {
    val currentName: String = allCards[randomValue].cardName
    val currentValue: Int = allCards[randomValue].cardValue
}

I can get the cardName value from the list, but when I try to get the cardValue it just says: unresolved reference: cardValue

What am I doing wrong?

1 Answers

You need to put val before cardValue (and possibly amountDeck if you plan to use it). What you currently have only allows you to specify it in the constructor (a primary constructor parameter), but what you want is a class parameter.

class Cards(val cardName: String = "", val cardValue: Int = 0, val amountDeck: Int = 4)

Cards("One", 1).cardValue // works!
Related