柯里化方法:
package cn._51doit.day06
object KelyDemo {
def m1(x: Int, y: Int): Int = x * y
//定义一个柯里化方法
def m2(x: Int)(y: Int) = x * y
def m3(x: Int)(y: Int)(z: Int) = x * y * z
def main(args: Array[String]): Unit = {
val r1 = m1(5, 6)
println(r1)
val r2 = m2(5)(6)
println(r2)
val r3 = m3(5)(6)(7)
println(r3)
val arr = Array(1,2,3,4,5)
arr.fold(0)(_+_)
arr.aggregate(0)(_+_, _+_)
val f2 = m2 _
println(f2)
//f2: Int => (Int => Int) = <function1>
//传入部分参数,然后用空格下划线,会生成一个函数,相当于传入了一个参数
val f3 = m2(5) _
f3(8) // 5 * 8
}
}
隐式参数:
object ImplicitVariableDemo {
implicit val i = 111
//两个参数必须都得传入
def m(x: Int, y: Int): Int = {
x * y
}
//方法中参数的默认值必须写在后面
def m1(x: Int, y: Int = 8): Int = {
x * y
}
//使用柯里化方法,参数传入默认值,必须用implicit关键字修饰
def m2(x: Int)(implicit y: Int = 8): Int = {
x * y
}
def main(args: Array[String]): Unit = {
//val r1 = m(5, 8)
//val r2 = m1(5, 10)
//println(r2)
//val r3 = m2(7)(9)
//println(r3)
//调用m2这个方法,传入一个参数,第二个参数使用有默认值的隐式参数
//隐式参数:在编译时,会在程序的上下文中查找跟这个隐式参数类型一样的变量,有就传入。
//优先级:传入的 > 上下文的类型一致的隐式参数 > 方法中的默认参数
//上下文中不能存在多个类型一样的隐式参数,无法自动识别用哪一个,会报错
val r4 = m2(6)(1111)
println(r4)
}
}
隐式转换的导入
定义一个含有隐式转换参数的类
class MyClassContext {
implicit val aaa = 111
implicit val bbb = 111.111
}
定义一个含有隐式转换参数的object对象
object MyContext {
implicit val aaa = 111
implicit val bbb = 111.111
}
object ImplicitVariableDemo {
//implicit val i = 111
//implicit val j = 1111111
//两个参数必须都得传入
def m(x: Int, y: Int): Int = {
x * y
}
def m1(x: Int, y: Int = 8): Int = {
x * y
}
//使用柯里化方法,参数传入默认值,必须用implicit关键字修饰
def m2(x: Int)(implicit y: Int): Int = {
x * y
}
def main(args: Array[String]): Unit = {
//val r1 = m(5, 8)
//val r2 = m1(5, 10)
//println(r2)
//val r3 = m2(7)(9)
//println(r3)
//调用m2这个方法,传入一个参数,第二个参数使用有默认值的隐式参数
//隐式参数:在编译时,会在程序的上下文中查找跟这个隐式参数类型一样的变量,有就传入。
//优先级:传入的 > 上下文的类型一致的隐式参数 > 方法中的默认参数
//上下文中不能存在多个类型一样的隐式参数
//import MyContext._ object对象直接导入
val context = new MyClassContext
//如果是类,先new该类的实例
import context._
val r4 = m2(6)
println(r4)
1 to 10
}
}
隐式转换案例:
导入Int的包装类RichInt (IntWrapper),1 to 10,1.to (10),1 until 10
待导入的隐式转换对象MyContext
import java.io.File
object MyContext {
implicit val aaa = 111
implicit val bbb = 111.111
implicit def fileToRichFile(file: File): RichFile = new RichFile(file)
}
import java.io.File
import scala.io.Source
import MyContext._
class RichFile(val file: File) {
def read(): String = {
Source.fromFile(file).mkString
}
}
object RichFile {
def main(args: Array[String]): Unit = {
val file = new File("/Users/xing/Desktop/word.txt")
// 1 to 10 , Int类上没有to方法,就会报错,但是调用后发现可以调用,说明有一个增强的to方法
//调用File类上的read方法,File类上没有read方法,直接报错!我想方设法让它不报错,添加一个增强的read方法
//Int上没有to方法,可以在RichInt中扩展一个to方法,同理File上没有read方法,可以在RichFile扩展增强一个read方法
//包装、装饰模式:显式的包装
//val richFile = new RichFile(file)
//val content = richFile.read()
val content = file.read()
println(content)
}
}
//如果既有相同功能的隐式转换方法和函数,优先调用隐式转换函数,没有函数才调用方法。