Scala函数:
- 函数是Scala的核心
- 函数的定义:
def 函数名(参数列表):返回值={
函数体
return [表达式]
}
- 函数调用:
函数名(参数列表)
匿名函数:
- 指不含函数名称的函数
- 匿名函数的定义:
(参数列表)=>{函数体}
//例
(x:Int)=>x*x
(x:Int)=>{println(x);x*x}
() => { System.getProperty("user.dir") }
val f1=(x:Int)=>{println(x);x*x}
f1(2)
函数柯里化(Currying):
把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术
函数柯里化的定义:
def myfun(x:Int,y:Int) = ((x%y)==0)
//柯里化
def myfun(x:Int)(y:Int) = ((x%y)==0)
//新函数接收剩余的参数列表作为其参数
def f1(x:Int,y:Int) = myfun(x)(y)
def f2(x:Int) = myfun(x)(10)
def f3 = (y:Int) = myfun(10)(y)
def f4 = myfun(10)(_)
隐式函数:
1.方法可以具有隐式参数列表,由参数列表开头的implicit 关键字标记
2.Scala可自动传递正确类型的隐式值
def sum(x:Int)(implicit y:Int)=x+y
implicit var a=10 //将作为Int类型隐式值自动传递
sum(10) //20
隐式转换:
隐式转换触发机制:
- 当表达式的类型与预期的类型不同时
- 当对象访问一个不存在的成员
- 当对象调用某个方法,而方法的参数声明与传入参数不匹配时
implicit常见的用法:
- 使用implicit 可以实现——隐式参数
object ImplicitTest {
/**
* Implicit实现隐式参数
*/
object Context{
implicit val str:String = "implicit parameter"
}
object Parameter{
def print(context:String)(implicit prefix:String): Unit ={
println(prefix+":"+context)
}
}
def main(args: Array[String]) {
Parameter.print("Hello")("Scala")
//在此使用隐式参数
import Context._
Parameter.print("Scala")
}
}
/***************************************************/
运行结果:
Scala:Hello
implicit parameter:Scala
//如果已经传入了隐式参数,则用传入值作为参数,如果没有指定隐式参数,则用默认给出的隐式参数值作为参数传入
2.使用implicit 可以实现—— 隐式转换
示例一:
class RichFile(val file:File){
def read= Source.fromFile(file.getPath).mkString
}
object Context{
implicit def file2RichFile(f:File)=new RichFile(f)
}
object ImplicitDemo {
def main(args: Array[String]) {
/**
* 在此使用了隐式转换
*/
import Context.file2RichFile
println(new File("c://user//document.txt").read)
}
}
/********************************************************/
示例二:
class ImplicitTransform {
def display(str:String)=println(str)
/**
*隐式转换函数
*/
implicit def typeConvertor(arg:Int) =arg.toString
implicit def typeConvertor(arg:Boolean)=if(arg) "true" else "false"
def main(args: Array[String]) {
display(123)
}
}
备注:
1.隐式转换函数个函数名无关,只与传入参数类型和返回类型有关
2.在同一个函数作用域下,不能同时有两个相同输入类型和返回类型的函数
“_” 常用场景
- 模式匹配
- 匿名函数
- 导入包中的所有工具类
- 占位符
- 函数赋值
//1.模式匹配
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything else"
}
Some(5) match { case(_) => println("Yes")}
//2.匿名函数
List(1,2,3,4,5).foreach(print(_))
List(1,2,3,4,5) foreach{ _ => print("hi")}
List(1,2,3,4,5).foreach( a => print(a))
}
//3.import导入包中所有类,类似java中的*
import scala.util.matching._
//4.占位符
List(1, 2, 3, 4, 5) map( _ + 2)
List(1, 2, 3, 4, 5) filter( _%2 == 0)
List(1, 2, 3, 4, 5) reduce( _ + _ )
List(1, 2, 3, 4, 5) exists( _ > 3)
List(1, 2, 3, 4, 5) takeWhile( _ < 4 )
//5.函数赋值
def fun = {
println("call")
}
val v = fun //调用函数 fun
val f = fun _ //将函数fun赋值给f