[英]Type mismatch error (Scala)
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 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中的一個表達式,因此它可以求值。 如果不輸入,則編譯器將為您放置()
類型為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
}
順便說一下,在case類中不需要val
無論如何它將是val
。 這應該是這樣的:
case class Item(brand: String, count: Int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.