1. 程式人生 > >Scala學習筆記(2)—— Scala 函式

Scala學習筆記(2)—— Scala 函式

1 函式的定義

def 方法名(引數名:引數型別):返回值型別 = {
    // 方法體

    //方法體內的最後一行是返回值,不需要 return
}
  • 當函式沒有輸入的引數,呼叫的時候可以不寫括號
package com.scalatest.scala.function

object FunctionApp {

  def main(args: Array[String]): Unit = {
   // println(add(2,3))
    println(three())
    println(three)

  }

  def add(
x: Int, y: Int): Int = { x + y } def three() = 1+2 }

2 預設引數

def main(args: Array[String]): Unit = {
    sayName()
    sayName("Jenny")
  }

  def sayName(name:String = "Mike")={
      println("hi :" + name)
  }

在這裡插入圖片描述

3 命名引數

呼叫函式的時候可以不按照引數的順序傳參

package com.scalatest.scala.function

object
FunctionApp { def main(args: Array[String]): Unit = { println(speed(100, 25)) println(speed(distance = 100, time = 25)) println(speed(time = 25, distance = 100)) } def speed(distance: Float, time: Float): Float = { distance / time } }

4 可變引數

object FunctionApp {
def main(args: Array[String]): Unit = { println(sum(1,2,3,4,5)) } def sum(nums: Int*): Int = { var res = 0 for (num <- nums) { res += num } res } }

5 迴圈表示式

5.1 to(左閉右閉)

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

5.2 until

在這裡插入圖片描述

5.3 for

package com.scalatest.scala.function
object FunctionApp {
    def main(args: Array[String]): Unit = {
        for (i <- 1 to 10) {
            print(i+" ")
        }
        println()
        for (i <- 1 to 10 if i%2==0){
            print(i+" ")
        }
    }
}

在這裡插入圖片描述

package com.scalatest.scala.function

object FunctionApp {
    def main(args: Array[String]): Unit = {

        val courses = Array("Hadoop","Spark","Hbase")
        
        for(ele <- courses){
            println(ele)
        }

        courses.foreach(ele => println(ele))

    }

}

5.4 while

package com.scalatest.scala.function

object FunctionApp {
    def main(args: Array[String]): Unit = {

        var (num, sum) = (100, 0)
        while (num > 0) {
            sum += num
            num = num - 1
        }

        println(sum)
    }

}