ITPub博客

首页 > 大数据 > 数据挖掘 > 深圳大数据学习:方法的嵌套--【千锋】

深圳大数据学习:方法的嵌套--【千锋】

原创 数据挖掘 作者:andy888168 时间:2019-10-22 15:36:38 0 删除 编辑

深圳大数据学习: 方法的嵌套 -- 【千锋】

方法里嵌套定义其他方法

示例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/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
莫安迪分享各类资讯文章

注册时间:2019-09-02

  • 博文量
    69
  • 访问量
    43789