[learning Scala] Functions 基礎

object SparkTest003 {
  def main(args: Array[String]): Unit = {
  /*
   * Chapter 4 functions
   */

    def jump(title: String = ""): Unit = print(s"\n ---------${title}----------- \n")

    // a scala function is a named wrapper for an expression
    def greeting = "greeting!"
    print(greeting)
    print("\n")

    // def <identifier>: <type> = <expression>
    def greeting2: String = "greeting with return value!"
    def greeting2_1(): String = "greeting with empty parenthesis!" // Functions with Side Effects Should Use Parentheses
    print(s"func: ${greeting2}\n")

    //def <identifier>(<identifier>: <type>[, ... ]): <type> = <expression>
    def greeting3(x: Int, y: Int): String = {
      s"x: $x, y: $y, res: ${x * y}"
    }
    print(s"${greeting3(3, 4)}\n")

    // A procedure is a function that doesn’t have a return value.
    def logs(d: Double): Unit = println(f"the value is $d%.2f")
    logs(3.1415926)

    jump("Invoking a Function with an Expression Block")
    def formatArea(a: Double): Double = {
      f"$a%.3f".toDouble
    }
    print {
      formatArea {
        val r = 1.0
        val pai = 3.1415
        r * pai
      }
    }

    jump("recursive function")
    //@annotation.tailrec
    def fibonacci (n: Long): Long = {
      if (n > 1) fibonacci(n - 1) + fibonacci(n - 2)
      else 1L
    }

    // can't be auto change to tail recursive, because the final expression is sum, not call functions
    def fibonacci_tail_recursive (n: Long): Long = {
      if (n <= 1) 1L
      else fibonacci_tail_recursive(n - 1) + fibonacci_tail_recursive(n - 2)
    }

    @annotation.tailrec
    def pow(x: Int, n: Int, res: Int = 1): Int = {
      if (n <= 0) res
      else pow(x, n - 1, res * x)
    }
    print(fibonacci_tail_recursive(10L))
    print(s"\nres: ${pow(3, 3)}")

    jump("nested functions")
    def max(x: Int, y: Int, z: Int): Int = {
      def max(x: Int, y: Int): Int = if (x < y) y else x
      max(x, max(y, z))
    }
    print(s"the max of three numbers is : ${max(1, 3, 2)}")

    jump("Calling Functions with Named Parameters")
    def greet(prefix: String, name: String): Unit = {
      print(s"hello: ${prefix} ${name}\n")
    }
    greet("Ms", "Sandy")
    greet(name = "Sandy", prefix = "Ms")

    jump("Vararg Parameters")
    def count(items: Int*): Int = {
      var cnt = 0
      for (i <- items) cnt += 1
      cnt
    }
    print(count(1, 2, 3, 4))

    jump("Type Parameters: like C++ template")
    def identify[A](a: A): A = a
    val d: Double = identify[Double](3.14)
    val dd: Double = identify(3.14)
    val ddd = identity(3.14)

    val s: String = identify[String]("hello type parameters")
    val ss: String = identify("hello type inference")
    val sss = identity("hello type inference and return inference!")
    print(s"d is : ${ddd}, s is: ${sss}")

    jump("Methods and operators")
  }
}
相關文章
相關標籤/搜索