Aim of the code: Class Pair can print out Product name and quantity, Product name stored in Class Product
class Pair<T, U>(var product: Product, var quantity: Int) {
for ( (product,quantity) in productAndQuantityList) {
println("Name: ${product.productName}")
println("Quantity: $quantity")
}
}
Above Error:(2, 9) Kotlin: Expecting member declaration Error:(2, 57) Kotlin: Function declaration must have a name
class ShoppingCart{
private val productAndQuantityList = mutableListOf<Pair<Product,Int> >()
...
}
open class Product(
val productName: String,
var basePrice: Double,
open val salesPrice: Double,
val description: String) {
...}
Thanks!
If you want to run the for loop when the object is instantiated, then you should use an initializer. You can't simply put statements inside class definitions directly.
class Pair<T, U>(var product: Product, var quantity: Int) {
init {
for ( (product,quantity) in productAndQuantityList) {
println("Name: ${product.productName}")
println("Quantity: $quantity")
}
}
}
However, this code is wrong because Pair does not have access to productAndQuantityList, although ShoppingCart does. As Mathias Henze suggested, you should make a function in ShoppingCart and move the for loop into that, like this:
fun printProducts() {
for ( (product,quantity) in productAndQuantityList) {
println("Name: ${product.productName}")
println("Quantity: $quantity")
}
}
As for your Pair class, the type parameters T and U are unnecessary, as you don't use them anywhere, and the class itself is provided by the standard library (The header looks something like data class Pair<out A, out B>(val first: A, val second: B).
If you're determined to use your own Pair class, be sure to make it a data class, so it can be destructured, and change the type of productAndQuantityList to mutableListOf<Pair> (without the type parameters Pair<Product, Int>).
Please read the answer by Mathias Henze, which is correct. My answer, was originally completely wrong, but I have now corrected it.
The productAndQuantityList is just for storing the data. The Pair class is a provided class by Kotlin. You don't need to add anything to it in your usecase.
The ability to print the product and the quantity should be a function of the ShoppingCart, so just have:
class ShoppingCart{
private val productAndQuantityList = mutableListOf<Pair<Product,Int> >()
// ...
fun printContents() {
for ( (product,quantity) in productAndQuantityList) {
println("Name: ${product.productName}")
println("Quantity: $quantity")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With