Methods with parameters

Don't you get tired of writing again and again the code to move by a fixed amount of steps? On the other hand, writing forward2(), forward3(), forward4(), as well as backward2(), backward3(), backward4(), and so on does not really help, to say the less.

Luckily, it is possible to pass parameters to your methods. You have to specify their type and name between the parenthesis after the method name. Then, you can use them in the method body as if it were variables defined in there, and which initial value is what the caller specified.

[!java]double [/!]divideByTwo([!java]double [/!]x[!scala]: Double[/!])[!scala]: Double =[/!] [!java|scala]{[/!][!python]:[/!]
     return x / 2[!java];[/!]
[!scala|java]}[/!]

As caller, you have to specify the initial value of this "variables" between the call's parenthesis.

[!java]double [/!][!scala]val [/!]result = divideByTwo(3.14)[!java];[/!]

If you want several parameters, you need to separate them with comas (,) both in the declaration and calls.

[!java]double divide(double x, double y) {[/!]
[!scala]def divide(x:Double, y:Double): Double = {[/!]
[!python]def divide(x, y):[/!]
     return x / y[!java];[/!]
[!java|scala]}[/!]
[!java]double res = divide(3.14 , 1.5);[/!]
[!scala]val res = divide(3.14 , 1.5)[/!]
[!python]res = divide(3.14 , 1.5)[/!]
[!java|scala]

In [!thelang], you can declare several methods of the same name as long as they don't have the same signature, that is, the same amount of parameters and the same parameters' types.

[!java]double max(double x, double y)[/!][!scala]def max(x:Double, int y:Double): Double =[/!] {
  if (x > y) {
    return x;
  }
  return y;
}[!java]int max(int x, int y)[/!][!scala]def max(x:Int, int y:Int): Int =[/!] {
  if (x > y) {
    return x;
  }
  return y;
}
[!java]int max(int x, int y; int z)[/!][!scala]def max(x:Int, int y:Int, int z:Int): Int =[/!] {
  if (x > y && x > z) {
    return x;
  }
  if (y > z) {
    return y;
  }
  return z;
}

Observe that we omitted the else branches of each if. It works anyway because a return interrupts the method execution. If we arrive to the last line of [!java]max(int,int)[/!][!scala]max(Int,Int):Int[/!], we know that x<=y because otherwise, the return of line 2 would have stopped the execution.

[/!]

Exercise goal

This time, you have to write a [!java]move(int stepCount,boolean forward)[/!] [!scala]move(stepCount: Int,forward: Boolean)[/!] [!python]move(stepCount,forward)[/!] method which moves forward by stepCount steps if forward is true, and moves back of that amount of steps if the boolean is false.

This time, there is only one world but seven buggles, all sharing the same code. This code should not be really problematic for you to write, actually.