深圳大数据学习: 方法的嵌套 — 【千锋】
方法里嵌套定义其他方法
示例1
object EmbedDemo {
def add3 (x:Int,y:Int,z:Int)={
def add2 (x:Int,y:Int)={
x+y
}
add2 ( add2 (x,y),z)
}
def main (args: Array[String]): Unit = {
println ( add3 ( 1 , 2 , 3 )) //6
}
}
示例2
def factorial (x: Int): Int = {
def fact (x: Int, accumulator: Int): Int = {
if (x <= 1 ) accumulator
else fact (x – 1 , x * accumulator)
}
fact (x, 1 )
}
println ( “Factorial of 2: “ + factorial ( 2 ))
println ( “Factorial of 3: “ + factorial ( 3 ))
方法的多态
Scala里方法可以通过类型实现参数化,类似泛型。
def listOfDuplicates[A](x: A, length: Int): List[A] = {
if (length < 1 )
Nil
else
x :: listOfDuplicates (x, length – 1 )
}
println (listOfDuplicates[Int]( 3 , 4 )) // List(3, 3, 3, 3)
println ( listOfDuplicates ( “La” , 8 )) // List(La, La, La, La, La, La, La, La)