Jordan Tranchina
Jordan Tranchina

Reputation: 75

How do I specify an element in a function when calling upon a class's array in Kotlin?

Expectation: console prints: "Making 2 cups of Light coffee"

Reality: Error:(2, 30) Kotlin: The integer literal does not conform to the expected type Array

//Class
class CoffeeMaker(
        var strength: Array<String> = arrayOf("Light", "Medium", "Dark"),
        var cups: Int? = null
) {
    fun brewCoffee() {
        println("Making $cups cups of $strength coffee")
    }
}

// Main.kt
fun main() {
    val coffee = CoffeeMaker(0, 2)
    coffee.brewCoffee()
}

Upvotes: 0

Views: 74

Answers (3)

matt freake
matt freake

Reputation: 5090

It sounds like you want strength to be an option, for how strong the coffee is, and as such one CoffeeMaker should have just one strength property. An array stores 0 or more things so currently your coffee maker could 0 strengths or a million or whatever.

An Enum represents a single value from a fixed list of options and is probably what you want. You don't need to refer to the item by its index, just the strength itself

enum class CoffeeStrength {  LIGHT, MEDIUM, DARK }

//Class
class CoffeeMaker(
    var strength: CoffeeStrength,
    var cups: Int? = null
) {
    fun brewCoffee() {
        println("Making $cups cups of $strength coffee")
    }
}

// Main.kt
fun main() {
    val coffee = CoffeeMaker(CoffeeStrength.LIGHT, 2)
    coffee.brewCoffee()
}

Upvotes: 3

Animesh Sahu
Animesh Sahu

Reputation: 8096

You are passing the index of the element in the constructor as an argument, you should create a static array in the companion object that stores the information and accept an index of type Int that could be used later to get element at that index from the availableStrength array predefined statically.

class CoffeeMaker(
        var strengthIndex: Int,
        var cups: Int? = null
) {
    fun brewCoffee() {
        println("Making $cups cups of ${availableStrength[strengthIndex]} coffee")
    }

    companion object {
        val availableStrength: Array<String> = arrayOf("Light", "Medium", "Dark")
    }
}

Upvotes: 0

Simulant
Simulant

Reputation: 20102

You are passing two integers into the constructor, but your constructor only accepts an Array of Strings and optional an Int.

so what you can do is:

// strength 0. 2 cups
val coffee = CoffeeMaker(arrayOf("0"), 2)

or

// strength 0, 2. null cups
val coffee = CoffeeMaker(arrayOf("0", "2"))

The first argument has to be an array of Strings. To make the 0 (integer) a String you need to double quote it. And then you need to wrap it into an array.

Kotlin doesn't have a literal constructor for arrays like other languages have e.g.: {"0", "2"} or ["0", "2"]

Upvotes: 0

Related Questions