简体   繁体   中英

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)
  }
}

How would one add if else statements to this code so that the amount must be greater than 0? When I add an if statement I get a type mismatch error.

The problem is that your the function doesn't always return, functions always have to return single value. What happens when amount is not greater that zero? I suppose you need to return item as it is. We fix it by adding an else statement.

def add(amount:Int, item: Item): Item = {
if(amount>0)    
  item.copy(count = item.count+amount)
else
  item     
}

if is an expression in scala so it evaluates to something. If you don't put else compiler will put there () for you which is of type Unit . This will make your expression return Unit or Item . Their common supertype is Any so type of this expression is effectively Any while expected type is Item

def add(amount: Int, item: Item): Item = {
  if(amount > 0)    
    item.copy(count = item.count + amount)     
}

If you want to require the amount to be greater than zero just check it and throw exception if it's not. You can use builtin require for this.

def add(amount: Int, item: Item): Item = {
  require(amount > 0)    
  item.copy(count = item.count + amount)     
}

or you can handle this silently and don't modify item if wrong argument is passed

def add(amount: Int, item: Item): Item = {
  if(amount > 0)    
    item.copy(count = item.count + amount)
  else
    item
}

By the way you don't need vals in case class, it will be val anyway. This is how it should be:

case class Item(brand: String, count: Int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM