scala隐式转换

implicit隐式转换的使用

1、修饰变量

调用隐式类型参数的方法,在不传参数的情况下,编译器会在定义域范围内搜索隐式类型变量,自动传入

1
2
3
4
5
6
7
8
9
10
11
package test

object TestImplicit1 {
def main(args: Array[String]): Unit = {
val stu = new Student()
stu.print(20)
implicit val n:Int =22
stu.print
}
}

1
2
3
4
5
6
7
8
package test

class Student {
def print(implicit info:Int)={
println("学生年龄:"+info)
}
}

2、隐式方法

  • 参数传递错误,类型转换方法是隐式的,自动调用
1
2
3
4
5
6
7
8
9
package test

object TestImplicit1 {
def main(args: Array[String]): Unit = {
val stu = new Student()
implicit def toInt(s:String): Int ={Integer.parseInt(s)}
stu.print("50")
}
}
  • 功能扩展
1
2
3
4
5
6
7
8
9
10
11
package test

class Teacher {
implicit def teach(): Unit ={
println("他在讲课!!!")
}
def test(): Unit ={
println("考试!!!")
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package test

object TestImplicit1 {
def main(args: Array[String]): Unit = {
val stu = new Student()
implicit def toTeacher(s:Student): Teacher ={
new Teacher
}
stu.teach()
stu.test()
}
}

3、修饰类

隐式类需在对象中,主构造函数单参数。接收待转换对象入参,隐式类所有方法归参数所有。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package test

object Yszh {
implicit class Person(s:Student){
def test1(): Unit ={
println("test1")
}
def test2(): Unit ={
println("test2")
}
}
implicit class toUp(s:String){
def upCase(): String ={
s.map(c=>(c+1).toChar)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package test

object TestImplicit1 {
def main(args: Array[String]): Unit = {
val stu = new Student()
import Yszh.Person
stu.test1()
stu.test2()

import Yszh.toUp
println("abc".upCase())
}
}