Scala Function Exercise

package com.gsau.util.Chapter9
class FunctionTest {
  /**
    * Function literal (aka anonymous function)
    */
  val x = List.range(1, 100) //Create a normal list
  val y = x.filter ((i: Int) => i % 2 == 0) //passed in an anonymous function to create a new list with only even numbers
  val z = x. filter(_ % 3 == 0) //passed in An anonymous function creates a new list with only odd numbers, which is a simplified way of writing
  val double = (i: Int) => i * 2 //Assign the function literal to the variable
  //Explicitly declare the function return type as Different forms of Boolean (when the function has only one parameter)
  val f: (Int) => Boolean = (i: Int) => {
    i % 2 == 0
  }
  val f1: Int => Boolean = i => {
    i % 2 == 0
  }
  val f2: Int => Boolean = i => i % 2 == 0
  val f3: Int => Boolean = _ % 2 == 0
  val f4 = (i: Int) => i %2==0
  //The function accepts two Int parameters and returns the Int value of the input parameters and
  //1. Implicit way
  val add = (x: Int, y: Int) => {
    x + y
  }
  val add2 = (x: Int , y: Int) => x + y
  //2. Explicit way
  val add3: (Int, Int) => Int = (x, y) => {
    x + y
  }
  val add4: (Int, Int) = > Int = (x, y) => {
    x + y
  }
  val sum=(x:Int,y:Int,z:Int)=>{x+y+z}
  val f5=sum(1,2,_ :Int)

  /**
    * Create a function that returns a function
    * @param prefix
    * @return
    */
  def saySomeThing(prefix:String)=(s:String)=>{
      prefix+" "+s //(s:String)= >{prefix+" "+s} anonymous function
  }

  val sayHello=saySomeThing("Hello")

  /**
    * 定义一个接受函数作为参数的的方法
    */
  def method(fun: (Int, Int) => Int, index: Int, index2: Int) = {
    for (i <- 10 to index) {
      for (j <- 10 to index2) {
        var tmp = fun(i, j)
        println(tmp)
      }
    }
    val tmp = fun(11, 11)
    tmp
  }
}
package PackageTest {

  object testClass {
    def main(args: Array[String]): Unit = {
      val list = List.range(1, 100)
      val ts = new FunctionTest
      ts.z.foreach((i: Int) => print(i + " "))
      ts.x.foreach((i) => {
        if (i == 1) {
          println()
          print(i + "->")
        } else print(i + "->")
      })
      println("\n" + ts.double(1000))
      list.foreach (i => println(ts.f(i)))
      val fun: (Int, Int) => Int = (x, y) => {
        if (x > 10) {
          println(s"input parameter x=$ x is greater than or equal to 10 can be calculated")
          if (x > 10) {
            println(s"input parameter y=$y greater than or equal to 10 can be calculated")
            x * y
          } else {
            println(s"input parameter y=$y Less than 10 can not be calculated")
            0
          }
        } else {
          println(s" The input parameter x=$x is less than 10 and cannot be calculated")
          0
        }
      }
      println(ts.method(fun,15,15))
      println(ts.f5(5))
      println(ts.sayHello("Jhon"))
    }
  }

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324518911&siteId=291194637