1 /我的 blockquote 代码中有2个错误,我可以更改代码吗?
1.1 / Kotlin:期待元素 1.2 / Kotlin:使用提供的参数不能调用以下功能: 公共最终运算符fun减(其他:字节):int在kotlin.Int中定义
类别的目标:在具有新销售价格的产品下添加折扣产品
class DiscountProduct(
productName: String,
basePrice: Double,
salesPrice: Double,
description: String) :
Product(productName, basePrice, salesPrice, description) {
val discount = mutableListOf(DiscountType.SUMMER, DiscountType.SHORT, DiscountType.ALLAWAY, DiscountType.NODISC)
覆盖var salesPrice:Double = salesPrice *(100折扣)%
}
open class Product(
val productName: String,
var basePrice: Double,
open var salesPrice: Double,
val description: String) {...}
enum class DiscountType(disc:Int) {
SUMMER(20),
SHORT(10),
ALLAWAY(50),
NODISC(0)
}
2 /我应该学习哪个主题来再次避免相同的错误?
谢谢!
答案 0 :(得分:1)
因此,在这一行中,您有两个错误
override var salesPrice: Double = salesPrice*(100-discount)%
首先,您尝试从一百个对象中减去一个对象列表(在您的情况下为DiscountType
)。它不会以这种方式工作。您应该告诉您要执行此操作的确切程度。例如,通过编写另一个函数。像这样:
fun getDiscount(discounts : List<DiscountStatus>): Int{
return 100 - discounts.sumBy { it.disc }
}
或者您想使用折扣做任何事情。无论如何,编译器都不知道如何处理不同的类型(数字和DiscountType
对象的列表)。
第二,在语句的末尾添加一个%
符号。在Kotlin中,有这样一种运算符,但使用方式有所不同。您可能想将自己discount
应用于salesPrice
。同样,您必须告诉编译器您到底想怎么做。编写函数:
fun applyDiscount(price: Double, discount: Int): Double {
return price * (discount.toDouble() / 100.0)
}
或类似的东西。最后将所有这些组合成一个语句:
val discount = mutableListOf(DiscountType.SUMMER, DiscountType.SHORT, DiscountType.ALLAWAY, DiscountType.NODISC)
override var salesPrice: Double = applyDiscount(salesPrice, getDiscount(discount))
请自己进行整个计算,并以我的答案为例。 从算术运算开始,您应该真正学习Kotlin的基础知识。 https://kotlinlang.org/docs/reference/keyword-reference.html#operators-and-special-symbols