Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

6. Scala implicit conversion

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report