大数据——Scala函数

it2023-08-03  68

Scala函数

Java Lam表达式示例 内置四大函数式接口Scala函数示例 参数传递命名参数示例 参数缺省值匿名函数高阶函数中置表达式函数嵌套柯里化(Currying)隐式参数隐式函数闭包

Java Lam表达式

函数式接口

一种只含有一个抽象方法声明的接口可以使用匿名内部类来实例化函数式接口的对象通过Lambda表达式可以进一步简化代码

Lambda语法

(parameters) -> expression (parameters) ->{ statements; }

示例

//Java 8方式: new Thread() -> System.out.println("In java8,Lambda expression rocks !!") .start()

示例

实现加减乘除运算

//定义一个接口 public interface OperationInterface { public Integer operation(Integer a,Integer b); } //实现接口 public class TestDemo { public static void main(String[] args) { OperationInterface add = (Integer a, Integer b) -> a + b; OperationInterface jian = (Integer a, Integer b) -> a - b; OperationInterface ji = (Integer a, Integer b) -> a * b; OperationInterface chu = (Integer a, Integer b) -> a / b; /* Integer sum2=ji.operation(10, 20); System.out.println(sum2);*/ TestDemo demo = new TestDemo(); Integer result = demo.getResult(20, 10, add); System.out.println(result); /*OperationInterface operationInterface = new OperationInterfaceImpl(); Integer sum = operationInterface.operation(10, 10); System.out.println(sum);*/ } public Integer getResult(Integer a, Integer b, OperationInterface operationInterface) { return operationInterface.operation(a, b); } }

结果展示: 实现判断输入的字符,有a则返回1,有b则返回2,其他的则返回0

public interface ContainsInterface { public Integer containsinterface(String a); } public class TestContains { public static void main(String[] args) { ContainsInterface containszhi = (String a) -> { if (a.contains("a")) return 1; else if (a.contains("b")) return 2; else return 0; }; System.out.println(containszhi.containsinterface("ao")); } }

结果展示: 实现对输入字符的判断,来确定工资的多少

public interface XueshengInterface { public Integer xueshengInterface(String a, int b); } public class TestXuesheng { public static void main(String[] args) { XueshengInterface xueshengInterface=(String a,int b)->{ if(a.equals("初中")&& b==18) return 2000; else if(a.equals("高中") && b==18)return 2200; else if(a.equals("大专") && b==21) return 3000; else return 0; }; System.out.println(xueshengInterface.xueshengInterface("大专",21)); } }

内置四大函数式接口

消费接口:Consumer<T> 供给型接口:Supplier<T> 断言型接口:Predicate<T> 函数型接口:Function<T>

Consumer<String> consumer=(s)-> System.out.println(s.toUpperCase()); consumer.accept("testabc"); Supplier <Double> supplier = () -> Math.random(); System.out.println(supplier.get()); Predicate<String> condition=s -> s.length()>4; if(condition.test("hello")) System.out.println("true"); Function<String,String> toUpper=(s)->s.toUpperCase(); System.out.println(toUpper.apply("test"));

Scala函数

函数是Scala核心 函数定义

def 函数名([参数列表]):[返回值]={ //省略“:[返回值]=”则称为过程 函数体 return [表达式] }

函数调用

函数名(参数列表) def square(x: Int): Int = { println(x) x * x //return } def sayHello(x:String):Unit={ println("Hello ! "+x) }

示例

获取a,b的最大值和最小值

object test { //获取最小值 def main(args: Array[String]): Unit = { def minValue(a:Int,b:Int):Int={ if(a>b) return b else return a } println(minValue(10,20)) //获取最大值 def maxValue(a:Int,b:Int)=if(a>b) a else b println(maxValue(10,20)) } }

结果展示: 根据传入的运算符号,进行运算

object test { def main(args: Array[String]): Unit = { def yunsuan(a:Int,b:Int,c:String):Int={ if(c.equals("+")) return a+b else if (c.equals("-")) return a-b else if (c.equals("*")) return a*b else return a/b } println(yunsuan(10,5,"+")) println(yunsuan(10,5,"-")) println(yunsuan(10,5,"*")) println(yunsuan(10,5,"/")) } }

结果展示: 输入一个正整数,进行叠乘

object test { def main(args: Array[String]): Unit = { def chen(a:Int):Int= { var sum=1 for (i <- 1 to a) { sum = sum * i } return sum } println(chen(10)) } }

结果展示:

参数传递

传值调用(call-by-value)

//传值调用时,参数只在调用时计算一次,后续重复使用计算的结果 def square(x: Int): Int = { println(x) //3 x * x //计算3*3 } square(1+2) //先计算1+2

传名调用(call-by-name)

//传名调用时,参数在调用时不会计算,只有真正用到参数时才计算 def square(x: => Int): Int = { println(x) //计算1+2 x * x //计算(1+2)*(1+2) } square(1+2) //调用时不计算

命名参数

通常情况下,传入参数与函数定义的参数列表一一对应 命名参数允许使用任意顺序传入参数

def printName(first:String, last:String) = { println(first + " " + last) } //Prints "John Smith" printName("John","Smith") printName(first = "John",last = "Smith") printName(last = "Smith",first = "John")

示例

object test { def main(args: Array[String]): Unit = { def a(name:String,age:Int)={ println("hello"+name+",age:"+age) } a("老王",11) //参数的长度未知,通过*来表示,可以传入多个参数 def b(name:String,s:String*)={ println(name) for(a<-s){ println(a) } } b("kb09","老王","是个人") } }

结果展示:

参数缺省值

Scala函数允许指定参数的缺省值,从而允许在调用函数时不指明该函数

def printName(first:String="John", last:String="Smith") = { println(first + " " + last) } //Prints "John Smith" printName()

匿名函数

指不含函数名称的函数 匿名函数定义

"=>"左边为参数列表 (参数列表)=>(函数体)"=>"右边为函数体如果函数体包含多条语句,应使用"{}"包含 (x:Int)=>x*x (x:Int)=>{println(x);x*x} () => { System.getProperty("user.dir") } val f1=(x:Int)=>{println(x);x*x} f1(2)

高阶函数

高阶函数可以将其他函数作为参数或者使用函数作为输出结果 常用高阶函数

mapforeachfilterfold、foldLeft、foldRightreducezipflattenflatMap //函数作为参数 def doSquare(f:Int=>Int,p:Int)=f(p) def square(x:Int):Int=x*x doSquare(square,square(2)) //函数作为返回值 //返回类型为函数(Int=>Int) def doSquare()={ (x:Int)=>x*x } doSquare()(2)

中置表达式

中置(辍)表达式是对只有一个参数的方法调用的约定

当方法只有一个参数时,可以省略".“和”()" //示例1 1 to 10 //实际调用 1.to(10) //示例2 List(1,2,3).map(x=>x+1).foreach(println) //使用中置表达式 val f=(x:Int)=>x+1 List(1,2,3) map f foreach println

函数嵌套

Scala函数内可以定义函数,函数内的函数也称局部函数或者嵌套函数

//使用函数嵌套实现阶乘运算 def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) //不能在factorial()之外调用 }

柯里化(Currying)

方法可以定义多个参数列表,当使用较少的参数列表调用多参数列表的方法时,会产生一个新的函数,该函数接收剩余的参数列表作为其参数。这被称为柯里化

//单参数列表 def modN(n: Int,x: Int) = ((x % n) == 0) //多参数列表 def modN(n: Int)(x: Int) = ((x % n) == 0) //新函数接收剩余的参数列表作为其参数 def f1(x: Int) = modN(10)(x) def f2(n: Int) = modN(n)(10) def f3 = modN(10)(_)

隐式参数

方法可以具有隐式参数列表,由参数列表开头的implicit关键字标记

implicit只能修改最尾部的参数列表,应用于其全部参数Scala可自动传递正确类型的隐式值通常与柯里化函数结合使用 def sum(x:Int)(implicit y:Int)=x+y implicit var a=10 //将作为Int类型隐式值自动传递 sum(10) //20

隐式函数

隐式函数也称隐式转换,使用implicit修饰的函数 应用场景

类型转换 implicit def double2Int(x:Double)=x.toInt val i:Int=3.5 类型增强 implicit def bool2Int(x:Boolean)=if(x) 1 else 0 println(1+true)

闭包

闭包是依照包含自由变量的函数字面量在运行时创建的函数值 闭包是对函数本身及其所使用的自由变量的统一定义

val y=1 val add=(x:Int)=>x+y //add是闭包,y是自由变量

闭包的变量绑定

闭包可捕获自由变量的变化闭包对捕获变量作出的改变在闭包之外也可见
最新回复(0)