scala-隐式操作

1.隐式转换-手动导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 手动导入
// 定义 RichFile 类,用来丰富 File 类的功能
class RichFile(file: File) {
// 定义 read() 方法,用来讲数据读取到一个字符串中
def read(): String = {
Source.fromFile(file).mkString
}
}
// 定义单例对象 ImplicitDemo,该单例对象中有一个隐式转换方法
object ImplicitDemo {
// 隐式转换方法 file2RichFile,是用来将 File 对象转换成 RichFile 对象
implicit def file2RichFile(file: File): RichFile = new RichFile(file)
}

// 导入隐式转换
import ImplicitDemo.file2RichFile
// 创建普通的 File 对象,尝试调用其 read() 功能
val file = new File("J:\\大数据第一代项目\\scalaFlink\\data\\1.txt")
println(file.read())

2.隐式转换-自动导入

1
2
3
4
5
6
7
8
9
10
11
12
// 自动导入隐式转换
// 定义一个RichFile类,里面定义一个read方法
class RichFile1(file: File) {
def read() = Source.fromFile(file).mkString
}

// 自动导入隐式转换
// 需求:通过隐式转换,让file类的对象具有read功能
// 2.定义一个饮食转换方法,用来将普通的File对象->RichFile对象.
implicit def file2RichFile(file: File) = new RichFile1(file)
// 3. 创建file对象,尝试调用read()方法.
val file1 = new File("J:\\大数据第一代项目\\scalaFlink\\data\\1.txt")

3.隐式参数-手动导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 隐式参数: 如果方法的某个参数列表使用了implicit修饰,则该参数列表就是:隐式参数
// 手动导入
// 定义一个show 方法
delimit: (String, String)是个元组
def show(name: String)(implicit delimit: (String, String)) = delimit._1 + name + delimit._2
// 定义一个单利对象,用来给隐式参数设置默认值
object ImplicitParam {
implicit val delimit_default = ("<<<", ">>>")
}

// 隐式参数
// 1.手动导入隐式参数
import ImplicitParam.delimit_default
// println(show("hkj"))
println(show("hkj")("((", "))"))

4.隐式参数-自动导入

1
2
3
4
5
6
7
8
9
10
11
// 自动导入
// 定义show方法,接受一个姓名,再接受一个前缀和后缀
def show1(name: String)(implicit delimit: (String, String)) = delimit._1 + name + delimit._2

// 2.自动导入隐式参数
// 通过隐式值,力给隐式参数设置初始值.
// 由程序自动导入的
implicit val delimit_default = "<<<" -> ">>>"
// 3. 调用show1()方法,打印结果
println(show1("hkj"))
println(show1("hkj")("<<<" -> ">>>"))

5.案例:获取列表元素平均值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package hkjcpdd.stu

object ClassDemo14_fin {
// 1.定义一个RichList类,用来给普通的List添加avg方法,用于获取列表元素的平均值
class RichList(list: List[Int]) {
// 2.定义avg方法,用来获取List列表中的所有元素的平均值
def avg() = {
if (list.isEmpty) None
else Some(list.sum / list.size)
}
}

def main(args: Array[String]): Unit = {
// 获取列表元素平均值
// 3.定义隐式转换方法,用来将普通List独享转换为RichList对象
implicit def list2RichList(list:List[Int]) = new RichList(list)
// 4. 定义List列表,获取其中所有元素的平均值
val list1 = List(1, 2, 3, 4, 5)
println(list1.avg())
}
}

6.总结

隐式操作主要理解为:

1.将方法进行丰富(在需要时,编译器会自动将一种类型的元素转换为另一种类型,以便使用目标类型的功能)

2.将元素进行元素转换(在函数调用时,编译器会自动查找并传递隐式参数,从而简化代码)