Pass two values into a method and use its return value.

parameters-returns Parameters carry values into a method. The return value carries the result back to the caller.

Parameters and Returns

width
ParametersReturns.scala
Replay: real traced execution (multi-file project)
object Main {
  def area(width: Int, height: Int): Int = {
    width * height
  }

  def main(args: Array[String]): Unit = {
    val width = 3
    val height = 4
    val result = area(width, height)

    println("width=" + width)
    println("height=" + height)
    println("area=" + result)
  }
}
object Main {
  def area(width: Int, height: Int): Int = {
    width * height
  }

  def main(args: Array[String]): Unit = {
    val width = 5
    val height = 4
    val result = area(width, height)

    println("width=" + width)
    println("height=" + height)
    println("area=" + result)
  }
}
  1. width ← 3, height ← 4

    6def main(args: Array[String]): Unit = {7  val width→ 3 = 3 //@width=58  val height→ 4 = 49  val result = area(width3, height4)1011  println("width=" + width)
  2. def area(width: Int, height: Int): Int =

    1object Main {2  def area(width3: Int, height4: Int): Int = {3    width3 * height44  }
  3. result ← 12

    8    val height = 49    val result→ 12 = area(width3, height4)1011    println("width=" + width3)12    println("height=" + height4)13    println("area=" + result12)14  }15}
    outputwidth=3
    height=4
    area=12
  1. width ← 5, height ← 4

    6def main(args: Array[String]): Unit = {7  val width→ 5 = 58  val height→ 4 = 49  val result = area(width5, height4)1011  println("width=" + width)
  2. def area(width: Int, height: Int): Int =

    1object Main {2  def area(width5: Int, height4: Int): Int = {3    width5 * height44  }
  3. result ← 20

    8    val height = 49    val result→ 20 = area(width5, height4)1011    println("width=" + width5)12    println("height=" + height4)13    println("area=" + result20)14  }15}
    outputwidth=5
    height=4
    area=20

Follow the Parameters

  1. width starts as 3.
  2. height starts as 4.
  3. area(width, height) passes both values into the method.
  4. The method returns width * height.
  5. The caller stores 12 in result. | width | height | returned area | | --- | --- | --- | | 3 | 4 | 12 | | 5 | 4 | 20 |

Exercise: ParametersReturns.scala

Reproduce width=3, height=4, and area=12, then use the pinned width variant 5 to predict area=20.