implicit parameter definition in class
implicit val odkaz = head;
def vypis(implicit odkaz:Prvek):String = {
odkaz match{
case null => ""
case e => e.cislo + " " + e.pocet + "\n" + vypis(e.dalsi)
}
}
...
def main(args:Array[String]){
开发者_JAVA百科 val q = new MyQueue() // insert some values
println(q.vypis)
}
This method(vypis) is a member of an queue-class so I'll always want to implicity start the recursion from the start of the queue, when calling the method from outside. Is there a way how to write it, that the method from outside calling, there's no paramter, but in inside, there's a parameter - for recursion...? The compiler complains that the parameter is not defined when called from outside
Or is there are way how can specify the default value for a method's parameter?
Using a nested method
def sum(list: List[Int]) = {
@annotation.tailrec
def sum(ls: List[Int], s: Int): Int = ls match {
case x :: xs => sum(xs, x + s)
case _ => s
}
sum(list, 0)
}
Using a default parameter for the accumulator
@annotation.tailrec
def sum(list: List[Int], s: Int = 0): Int = list match {
case x :: xs => sum(xs, x + s)
case _ => s
}
The second approach (only possible with Scala 2.8) unneccesarily broadens the public API, so I would recommend the first.
In Scala 2.8, default method (and constructor) parameters are available:
def m1(i: Int = 23): Int = i * 2
精彩评论