Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

6. Scala implicit conversion

Shulou Source: shulou.com Published: 2022-06-03 07:06:59 09月19日 Update

1. Scala implicit conversion usage scenarios

1. Used for conversion from one type to another.

2. For calls to methods with missing parameters

2. Scala implicit transformation classification

1. Implicit method

Implicit def intToString (x: Int) = x.toString

2. Implicit class

Implicit class RichFile (file: File) {

Def read = Source.fromFile (file) .mkString

}

New java.io.File (.). Read

3. Implicit object

Implicit object StringOrdering extends Ordering [String] {

Override def compare (x: String, y: String): Int = x.length-y.length

}

4. Implicit variables

Implicit val test = 5

5. Implicit parameters

Implicit val test = 5

FindAnInt

Def findAnInt (implicit x: Int) = x

III. Implicit conversion rules

1. If the expression does not meet the type required by the compiler, the compiler looks for implicit conversions that can make it meet the type requirements

2. If there is no member e in the T type, but we still want to access e through T.e, then the compiler looks for implicit conversions that can be applied to the T type and the return type contains the member e

IV. Rules for implicit search

1. The implicit entity is visible in the location where the lookup occurs (you can bind the implicit entity to the current scope through import)

2. If an implicit entity is not found according to the first rule, it will be found in all implicit entities contained in the implicit scope of the source type and target type (T).

2.1, type T and the accompanying object of its parent class

2.2. Accompanying classes of all type parameters of parameterized type T

2.3. type T or the object in which the type parameter of type T is located (object)

2.4, package object

Tags: Types parameters entities objects compilers rules compilers actions members methods variables can pass location scene location target expression or T.E classification Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi Shulou Information vpn Redmi