Scala隐式转换机制
概述
scala implicit关键字详解(隐式转换函数、隐式类、隐式参数、隐式值),implicit是scala中的一个关键字,关于它有着丰富的用法,使得scala更灵活和容易扩展。
implicit def int2str(x:Int):String = x.toString
这段代码声明了一个函数int2str,它与正常函数唯一的区别在于前面多出的implicit关键字。这里的implicit就是它字面的含义——隐式,它告诉编译器,这个函数是一个隐式转换函数,能够把Int类型的值转换成String类型的值。
知识点
- scala implicit关键字用于定义隐式方法、隐式类、隐式对象
- 隐式转换的作用:当一个转换不合法时,在当前的作用域能够找到对应的隐式转换,使得转换合法
- 定义隐式转换方法时,方法名自定义,但参数列表只能有一个
- 隐式转换不能存在二义性,即在同一作用域中,只有存在一种类型转换
- 通过隐式类,可以让用户灵活的自定义和扩充方法。注意:定义隐式类时,主构造器的参数只能有一个
object Demo10 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
val v1=100 //> v1 : Int = 100
//显式类型转换。格式固定:to指定类型
val v2:String=v1.toString() //> v2 : String = 100
//一、定义一个隐式转换方法
implicit def f1(x:Int)={x.toString()} //> f1: (x: Int)String
val v3:String=v1 //> v3 : String = 100
//二、隐式类
implicit class AuthMethod(x:String){
def suffix()={
x.takeRight(4)
}
def prefix()={
x.dropRight(4)
}
}
val s1="fil01.txt" //> s1 : String = fil01.txt
//调用suffix方法,获取文件名的后缀
s1.suffix //> res0: String = .txt
s1.prefix //> res1: String = fil01
//三、隐式对象
trait Adder[T]{
def add(x:T,y:T):T
}
def f2(a:Int,b:Int)(implicit adder:Adder[Int])={
adder.add(a,b)
} //> f2: (a: Int, b: Int)(implicit adder: Demo10.Adder[Int])Int
f2(2,3)(new Adder[Int]{
def add(x:Int,y:Int)={x+y}
}) //> res2: Int = 5
//隐式对象
implicit val a=new Adder[Int]{
def add(x:Int,y:Int)={x+y}
} //> a : Demo10.Adder[Int] = Demo10$$anonfun$main$1$$anon$2@7f63425a
f2(2,3)(a) //> res3: Int = 5
f2(2,3) //> res4: Int = 5
}
结尾练习:
object Demo09 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
//练习1:对"Hello"和"World"进行拉链操作,会产生什么结果?
val s1="hello" //> s1 : String = hello
val s2="world" //> s2 : String = world
//拉链方法:zip
//将对应项的数据合在一起,形成一个二元元组
val r1=s1.zip(s2) //> r1 : scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((h,w), (e
//| ,o), (l,r), (l,l), (o,d))
val a1=Array(1,2,3) //> a1 : Array[Int] = Array(1, 2, 3)
val a2=Array(7,8,9) //> a2 : Array[Int] = Array(7, 8, 9)
val r2=a1.zip(a2) //> r2 : Array[(Int, Int)] = Array((1,7), (2,8), (3,9))
//练习2:编写函数values(fun:(Int)=>Int,low:Int,high:Int),该函数输出一个集合,
//对应给定区间内给定函数的输入和输出。比如,-5,-4,-3,-2,-1,0,1,2,3,4,5
//values(x=>x*x,-5,5)应该产出一个对偶的集合(-5,25),(-4,16),(-3,9),…,(3,9),(5,25)
def values(f:(Int)=>Int,start:Int,end:Int)={
//用于存储结果
val result=scala.collection.mutable.ArrayBuffer[(Int,Int)]()
for(i<-start to end){
result.append((i,f(i)))
}
//返回结果集
result
} //> values: (f: Int => Int, start: Int, end: Int)scala.collection.mutable.ArrayB
//| uffer[(Int, Int)]
values(x=>x*x, -5, 5) //> res0: scala.collection.mutable.ArrayBuffer[(Int, Int)] = ArrayBuffer((-5,25)
//| , (-4,16), (-3,9), (-2,4), (-1,1), (0,0), (1,1), (2,4), (3,9), (4,16), (5,25
//| ))
}