Scala函数

一、方法

    方法定义
    Scala中 + - * / % 的作用和Java一样,但是特别的是,这些操作符实际上是方法。
    1 to 10
    1.to(10)
    
    def m2(a:Int,b:Int): Int = a * b
    
    def m1(a:Int,b:Int):Int = {
        a + b
    }
    def:定义方法的关键字
    m1:方法名
    a:参数列表
    b:参数列表
    Int:返回值类型
    a + b:函数体

二、函数

    1)方式1
    方法转换为函数
    方式:方法名 _
    res6: (Int, Int) => Int = <function2>
    <function2>
    代表一个函数,并且有两个参数。
    (Int, Int)
    代表参数列表
    Int
    代表返回值类型
    =>
    代表函数
    
    2)方式2
    定义函数:
    val h1 = (a:Int,b:Int) => {a * b}
    h1:函数名
    (a:Int,b:Int):函数的参数类型
    {a * b}:函数体

1、函数使用例子:

//1、定义方法m2计算a和b的积
scala> def m2(a:Int,b:Int):Int = a * b
m2: (a: Int, b: Int)Int

//2、调用方法m2
scala> m2(4,6)
res21: Int = 24

//3、方法m2转换为函数
scala> m2 _
res22: (Int, Int) => Int = <function2>

//4、定义一个参数的方法m1
scala> def m1(a:String) = println(a)
m1: (a: String)Unit

//5、调用方法m1
scala> m1("hello world")
hello world

//6、方法m1转换为函数
scala> m1 _
res24: String => Unit = <function1>

//7、定义两个参数的函数(简写)
scala> (a:Int,b:Int) => a * b
res25: (Int, Int) => Int = <function2>

//8、调用函数res25
scala> res25(5,8)
res26: Int = 40

//9、定义两个参数的函数(标准写法)
scala> (a:Int,b:Int) => {a * b}
res27: (Int, Int) => Int = <function2>

//10、定义函数h1
scala> val h1 = (a:Int,b:Int) => {a * b}
h1: (Int, Int) => Int = <function2>

//11、调用函数h1
scala> h1(4,9)
res28: Int = 36

三、传值调用&传名调用

    函数式编程:方法的参数可以是一个函数
    传值调用:
    1.先计算balance的值
    2.把这个值作为参数传递给printMoney
    传名调用:传递的是函数
    将balance方法的名称传递到方法内部执行

1、传值调用

package com.demo.scala02

/**
  * 传值调用
  * 1.先计算balance的值
  * 2.把这个值作为参数传递给printMoney
  */
object ZFBToPay {
  var money = 1000

  // 吃饭一次花50元
  def eat(): Unit = {
    money = money - 50
  }

  // 余额
  def balance(): Int = {
    //已调用一次eat方法
    eat()
    money
  }

  def printMoney(x: Int): Unit = {
    for(a <- 1 to 5){
      println(f"你的余额现在为:$x")
    }
  }

  def main(args: Array[String]): Unit = {
    eat()
    balance()
    printMoney(balance())
  }
}

输出结果

2、传名调用

package com.demo.scala02

/**
  * 传名调用
  * 传递的是函数
  * 将balance方法的名称传递到方法内部执行
  */
object ZFBToPay2 {
  var money = 1000

  // 吃饭一次花50元
  def eat(): Unit = {
    money = money - 50
  }

  // 余额
  def balance(): Int = {
    // 已调用一次eat方法
    eat()
    money
  }

  // 此时余额减了5次 x: => Int 表示的是一个方法的签名 没有参数 返回值是Int类型的函数
  def printMoney(x: => Int): Unit = {
    for(a <- 1 to 5){
      println(f"你的余额现在为:$x")
    }
  }

  def main(args: Array[String]): Unit = {
    // eat()
    // balance()
    printMoney(balance())
  }
}

输出结果

四、可变参数函数

    java中的可变参数:public static void m1(String ...arg){}
    scala中的可变参数:def sum(ints:Int*): Int ={}
    加了通配符*

1、java中的可变参数

package com.demo.scala02;

public class JavaTest {
    // java中的可变参数
    public static void m1(String ...args){

    }

    public static void main(String[] args) {
        m1("a");
        m1("a", "b", "c");
    }
}

2、scala中的可变参数

package com.demo.scala02

object ManyParam {
  // scala中的可变参数
  def sum(ints: Int*): Int = {
    var sum = 0
    for(v <- ints){
      sum += v
    }
    sum
  }

  /*
    不仅是可变参
    而且参数的类型不一致
    Any
   */
  def setName(params: Any*): Any = {
    return params
  }

  def main(args: Array[String]): Unit = {
    println(sum(1,2,3,4))
    println(sum(2,3))
    println(setName("John",18,188))
  }
}

输出结果

五、默认参数值函数

  如果传递了参数,则使用传递的值。如果不传递参数,则使用默认值。

1、例子

package com.demo.scala02

object DefaultParam {
  /*
    如果调用此方法且不给参数,要一个默认值。
   */
  def sum(a: Int = 3,b: Int = 7): Int = {
    a + b
  }

  def main(args: Array[String]): Unit = {
    // 如果传递了参数,则使用传递的值。如果不传递参数,则使用默认值。
    println(sum())
    println(sum(2,4))
  }
}

输出结果

六、高阶函数

    定义:将其他函数作为参数,或者其结果是函数的函数。

1、例子

package com.demo.scala02

object GaoJie {
  // 将其他函数作为参数,或者其结果是函数的函数
  def getPerson(h: Int => String,f: Int): String = {
    //函数h 参数f
    h(f)
  }

  def Person(x: Int) = "我是" + x.toString + "岁很帅的lz"

  def main(args: Array[String]): Unit = {
    println(getPerson(Person,18))
  }
}

七、部分参数应用函数

    如果函数传递所有预期的函数,则表示完全应用它了。
    如果只传递几个参数,并不是全部参数,那么将返回部分应用的函数。

1、例子

package com.demo.scala02

import java.util.Date

object PartParam extends App {
  def log(date: Date,message: String): Unit = {
    //参数打印
    println(s"$date,$message")
  }
  val date = new Date()
  val logMessage = log(date,_:String)

  log(date, "hello world")
  logMessage("2018马上要过去了!")
}

输出结果

2、命令行例子

scala> val sum = (a:Int,b:Int) => {a + b}
sum: (Int, Int) => Int = <function2>

scala> sum(1,)
<console>:1: error: illegal start of simple expression
sum(1,)
      ^

scala> sum(1,_:Int)
res0: Int => Int = <function1>

scala> res0(2)
res1: Int = 3

scala> res0(20)
res2: Int = 21

八、字符串的格式化输出

    文字插值器:f/s

1、例子

scala> val name = "lz"
name: String = lz

scala> var age = 18
age: Int = 18

scala> println("name:"+name+" age:"+age)
name:lz age:18

scala> println(f"name=$name age=$age")
name=lz age=18

scala> printf(s"name=$name age=$age")
name=lz age=18
scala> println(s"name=$name age=$age")
name=lz age=18

scala> println(s"1 + 1 = ${1+1}")
1 + 1 = 2

scala> println(f"1 + 1 = ${1+1}")
1 + 1 = 2

九、柯理化

    指的是将原来接收的两个参数的函数变为一个新的接收一个参数的函数,这样的一个过程。
    函数的通用性降低,但是适用性提高

1、例子

scala> def sum(a:Int,b:Int) = a + b
sum: (a: Int, b: Int)Int

scala> def sum(a:Int)(b:Int) = a + b
sum: (a: Int)(b: Int)Int

scala> sum(1,2)
<console>:13: error: too many arguments for method sum: (a: Int)(b: Int)Int
       sum(1,2)
          ^

scala> sum(1)(2)
res11: Int = 3

十、偏函数

    被包在花括号内没有match的一组case语句的是一个偏函数。
    PartialFunction[A,B]
    A: 参数类型
    B:返回类型
    常用与模式匹配。

1、例子

package com.demo.scala02

object PartialFunction {

  //定义函数
  def func(str: String): Int = {
    if(str.equals("lz")) 18 else 0
  }

  //定义偏函数
  def func1:PartialFunction[String, Int] = {
    //如果使用了偏函数必须用case
    case "lz" => 18
      //如果其他
    case _ => 0
  }

  def main(args: Array[String]): Unit = {
    println(func("lz"))
    println(func1("Lz"))
    println(func1("lz"))
  }
}

输出结果

原文地址:https://www.cnblogs.com/areyouready/p/10203244.html