隱式轉換
隱式轉換,也稱為檢視,是一種在多種情況下由編譯器套用的轉換
- 當遇到類型為
T
的表達式e
,但編譯器需要類型為S
的表達式時。 - 當遇到表達式
e.m
,其中e
的類型為T
,但T
未定義任何成員m
時。
在這些情況下,編譯器會在隱式範圍中尋找轉換,以將類型為 T
的表達式轉換為類型為 S
的表達式(或在第二種情況下轉換為定義成員 m
的類型)。
此轉換可以是
- 類型為
T => S
或(=> T) => S
的implicit def
- 類型為
scala.Conversion[T, S]
的隱式值
定義隱式轉換會發出警告,除非匯入 scala.language.implicitConversions
在範圍內,或將標記 -language:implicitConversions
提供給編譯器。
範例
第一個範例取自 scala.Predef
。由於這個隱式轉換,可以將 scala.Int
傳遞給預期 java.lang.Integer
的 Java 方法
import scala.language.implicitConversions
implicit def int2Integer(x: Int): java.lang.Integer =
x.asInstanceOf[java.lang.Integer]
第二個範例顯示如何使用 Conversion
為任意類型定義 Ordering
,並提供其他類型的現有 Ordering
import scala.language.implicitConversions
implicit def ordT[T, S](
implicit conv: Conversion[T, S],
ordS: Ordering[S]
): Ordering[T] =
// `ordS` compares values of type `S`, but we can convert from `T` to `S`
(x: T, y: T) => ordS.compare(x, y)
class A(val x: Int) // The type for which we want an `Ordering`
// Convert `A` to a type for which an `Ordering` is available:
implicit val AToInt: Conversion[A, Int] = _.x
implicitly[Ordering[Int]] // Ok, exists in the standard library
implicitly[Ordering[A]] // Ok, will use the implicit conversion from
// `A` to `Int` and the `Ordering` for `Int`.
本文內容