专栏原创出处:github-源笔记文件 (opens new window)github-源码 (opens new window),欢迎 Star,转载请附上原文出处链接和本声明。

Scala 编程语言专栏系列笔记,系统性学习可访问个人复盘笔记-技术博客 Scala 编程语言 (opens new window)

# 如何定义隐式转换

一个从类型 S 到类型 T 的隐式转换由一个函数类型 S => T 的隐式值来定义,或者由一个可转换成所需值的隐式方法来定义。

使用情况:

  1. 如果一个表达式 e 的类型为 S, 并且类型 S 不符合表达式的期望类型 T。

  2. 在一个类型为 S 的实例对象 e 中调用 e.m, 如果被调用的 m 并没有在类型 S 中声明。

# 情况 1-示例

implicit def int2Integer(x: String) : Integer =
  Integer.valueOf(x)

def add(a: Integer, b: Integer) = a + b
// "1"和"23"的类型都为 String,并不符合 add 方法需要的 Integer 类型。
// 由于定义了隐式转换,从上文找到了合适的隐式转换,String 被转成了 Integer, String => Integer
println(add("1","23"))

# 情况 2-示例

implicit def list2ordered[A](x: List[A]): Ordered[List[A]] =
  new Ordered[List[A]] {
    def compare(that: List[A]): Int = 1
  }

// List[Int] 本身是没有 compare 方法的,但是上面定义了隐式转换,List[A] => Ordered[List[A]]。
// 因此,List[Int] 类型的数据可以直接调用 compare 方法。
List(1,2,3).compare(List(3,2,1))
最后修改时间: 2/17/2020, 4:43:04 AM