首页 > 大数据 > 数据挖掘 > 深圳大数据学习:方法的嵌套--【千锋】
方法里嵌套定义其他方法
示例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)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69947096/viewspace-2660985/ ,如需转载,请注明出处,否则将追究法律责任。