Scala学习笔记(2)—— Scala 函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/85127956

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)
    }

}

猜你喜欢

转载自blog.csdn.net/u012292754/article/details/85127956
今日推荐