case class Item(val brand: String, val count: Int)
class Inventory {
def add(amount:Int, item: Item): Item = {
if(amount>0)
item.copy(count = item.count+amount)
}
def subtract(amount:Int, item: Item): Item = {
if(amount>0)
item.copy(count = item.count-amount)
}
}
如何将 if else 语句添加到此代码中,以便金额必须大于 0?当我添加 if 语句时,出现类型不匹配错误。
问题是你的函数并不总是返回,函数总是必须返回单个值。当amount
不大于零时会发生什么?我想你需要按原样返回item
。我们通过添加 else 语句来修复它。
def add(amount:Int, item: Item): Item = {
if(amount>0)
item.copy(count = item.count+amount)
else
item
}
if
是scala 中的一个表达式,因此它的计算结果是某些东西。如果你不放 else 编译器会为你放()
类型Unit
.这将使您的表达式返回Unit
或Item
。它们的共同超类型是Any
因此此表达式的类型是有效的Any
,而预期类型是Item
def add(amount: Int, item: Item): Item = {
if(amount > 0)
item.copy(count = item.count + amount)
}
如果您想要求金额大于零,只需检查它,如果不是,则抛出异常。为此,您可以使用内置require
。
def add(amount: Int, item: Item): Item = {
require(amount > 0)
item.copy(count = item.count + amount)
}
或者你可以静默地处理这个问题,如果传递了错误的参数,不要修改项目
def add(amount: Int, item: Item): Item = {
if(amount > 0)
item.copy(count = item.count + amount)
else
item
}
顺便说一句,你不需要 vals 以防万一,无论如何它都会val
。应该是这样的:
case class Item(brand: String, count: Int)