当前位置:网站首页>Application scenarios of large arrows in Scala

Application scenarios of large arrows in Scala

2022-06-13 03:28:00 TRX1024

scala in “=>” Application scenarios of

1、 Represents the return type of a function

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

    // Define a function variable 
    var x: (Int) => Int = test
    var x2: (Int) => String = test2
    println(x(2)) // 4
    println(x2(2)) // 2trx
  }

  def test(x: Int) = x * 2
  def test2(x: Int) = x+"trx"
(Int)=>Int、(Int)=>String  On the left is the parameter type , On the right is the return value type .

2、 Anonymous functions

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

    //   Define an anonymous function 
    var fun = (x: Int) => x * 2

    println(fun(10)) // 20

  }

Anonymous function definition , On the left is the parameter On the right is the function implementation (x: Int)=>{}

3、case sentence

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

    val x = 10
    val y = 10

    val value = x + y match {
      case 20 => x
      case 30 => y
    }

    print(value)
  }

In pattern matching match and try-catch Use both “=>” Represents the output result or returned value

4、By-Name Parameters( Named parameter )

The expression of a named parameter will not be evaluated before the function call , Instead, it will be wrapped into an anonymous function and passed as a function parameter , For example, a parameter whose parameter type is a nonparametric function is a named parameter .

object SayHello {
 
  def main(args: Array[String]): Unit = {
    println(" Value transfer call :")
    delayed0(time())
    println("===================")
 
    println(" Call by name :")
    delayed(time())
    println("===================")
  }
 
  def time() = {
    println(" Acquisition time , It's in nanoseconds ")
 
    System.nanoTime
  }
 
  def delayed0(t : Long)={
    println(" stay  delayed0  In the way ")
    println(" Parameters "+t)
    t
  }
 
  def delayed(t: => Long) = {  // The point is 
    println(" stay  delayed  In the way ")
    println(" Parameters : " + t)
    t
  }
}

 

原网站

版权声明
本文为[TRX1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529584360.html