大数据教程为大家分享Scala系列之方法的嵌套和方法多态
方法里嵌套定义其他方法
示例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)
原文地址:https://blog.51cto.com/14573321/2441897
时间: 2024-10-23 13:42:37