0

I'm trying to solve this problem.

In a package named "lecture" create an object named "FirstObject" with a method named "computeShippingCost" that takes a Double representing the weight of a package as a parameter and returns a Double representing the shipping cost of the package

• The shipping cost is ($)5 + 0.25 for each pound over 30

• Every package weighing 30 pounds or less will cost 5 to ship

• A package weighing 31 pounds cost 5.25 to ship

• A package weighing 40 pounds cost 7.50 to ship

Here's my scala code so far:

package lecture

object FirstObject {
  def computeShippingCost(weightOfpackage: Double): Double = {
    val shippingCost = 5
    if (weightOfpackage <= 30){
      return shippingCost
    }
    if (weightOfpackage >30){
      return (shippingCost) + (weightOfpackage - 30) * (.25)
    }

  }

  def main(args: Array[String]): Unit = {
    println(computeShippingCost(25.0)) // expect 5.0
  }
}

I keep receiving an error message saying

type: Mismatch, found:Unit, required: Double. 

What does that mean in the context of the problem and how do I fix it?

jwvh
  • 50,871
  • 7
  • 38
  • 64
indentation
  • 77
  • 2
  • 9

1 Answers1

3

In computeShippingCost there is a case that is not handled - and this returns Unit. In Scala every if needs to have an else. So your other case is if the last if does not match.

So what is needed is that you handle every possible case. And each of them must return a Double.

The correct code in Scala looks like:

def computeShippingCost(weightOfpackage: Double): Double = {
    val shippingCost = 5
    if (weightOfpackage <= 30){
      shippingCost
    } else {
      shippingCost + (weightOfpackage - 30) * 0.25
    } 
  }

By the way no return needed in Scala.

Check out this explanation: Return in Scala

pme
  • 14,156
  • 3
  • 52
  • 95