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

Implicit conversion and implicit parameters of Scala series

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Implicit conversion and implicit parameters of Scala series

5.1. Concept

Implicit conversion and implicit parameters are two very powerful functions in Scala. With implicit conversion and implicit parameters, you can provide an elegant class library to hide boring details from library users.

5.2. Action

Implicitly enhance the methods of the class to enrich the functionality of the existing class library

Object ImplicitDemo extends App {

/ / defines an implicit class that converts File into a defined implicit class RichFile

Implicit class RichFile (from:File) {

Def read:String = Source.fromFile (from.getPath) .mkString

}

/ / use implicit classes to extend the kinetic energy of existing classes

Val contents = new File ("src/test1.txt") .read

Println (contents)

}

5.5. Implicit class

When you create an implicit class, you only need to precede the corresponding class with the implicit keyword. For example:

Object Helpers {

Implicit class IntWithTimes (x: Int) {

Def times [A] (f: = > A): Unit = {

Def loop (current: Int): Unit =

If (current > 0) {

F

Loop (current-1)

}

Loop (x)

}

}

}

This example creates an implicit class called IntWithTimes. This class contains an int value and a method named times. To use this class, simply import it into scope and call the times method. For example:

Scala > import Helpers.

Import Helpers.

Scala > 5 times println ("HI")

HI

HI

HI

HI

HI

When using an implicit class, the class name must be visible and unambiguous in the current scope, which is similar to other implicit type conversions such as implicit values.

Can only be defined within other trait/ classes / objects.

Object Helpers {implicit class RichInt (x: Int) / / correct! } implicit class RichDouble (x: Double) / / error!

The constructor can only take one non-implicit parameter.

Implicit class RichDate (date: java.util.Date) / / correct!

Implicit class Indexer [T] (collecton: Seq [T], index: Int) / / error!

Implicit class Indexer [T] (collecton: Seq [T]) (implicit index: Index) / / correct!

Although we can create implicit classes with multiple non-implicit parameters, these classes cannot be used for implicit conversion.

Within the same scope, no method, member, or object can have the same name as an implicit class.

Object Bar

Implicit class Bar (x: Int) / / error!

Val x = 5

Implicit class x (y: Int) / / error!

Implicit case class Baz (x: Int) / / error!

5.6. Implicit conversion function

Is a function with a single argument declared with the implicit keyword, which is automatically referenced to convert values from one type to another.

Using implicit conversions to convert variables to the expected type is the first place the compiler uses implicit. This rule is very simple. When the compiler sees type X and needs type Y, it looks in the current scope to see if there is an implicit definition from type X to type Y.

For example, in general, double-precision real numbers cannot be used directly as integers because precision is lost:

Scala > val i:Int = 3.5

: 7: error: type mismatch

Found: Double (3.5)

Required: Int

Val i:Int = 3.5

^

Of course, you can call 3.5.toInt directly.

Here we define a definition of implicit type conversion from Double to Int, and then assign 3.5 to integers so that there is no error.

Scala > implicit def doubleToInt (x:Double) = x toInt

DoubleToInt: (X: Double) Int

Scala > val i:Int = 3.5

I: Int = 3

At this point, the compiler sees a floating point number 3.5, and the current assignment statement requires an integer. Normally, the compiler will report an error, but before reporting an error, the compiler will search for whether an implicit type conversion from Double to Int is defined. In this case, it found a doubleToInt. So the compiler will put

Val i:Int = 3.5

Convert to

Val i:Int = doubleToInt (3.5)

This is an example of implicit conversion, but automatic conversion from floating-point numbers to integers is not a good example because of the loss of precision. Scala automatically converts integers to double-precision real numbers when needed, because a

Implicit def int2double (x:Int): Double = x.toDouble

Scala.Predef is automatically introduced into the current scope, so the compiler automatically converts integers to Double types when needed.

5.7. Implicit parameter

Object Test {

Trait Adder [T] {

Def add (XRL TJY YRU T): t

}

Implicit val a = new Adder [Int] {override def add (xInt): Int = xperiy} def addTest (implicit adder: Adder [Int]) = {adder.add (xperiy)}

AddTest (1 ~ 2) / / correct, = 3

AddTest (1) (a) / / correct, = 3

AddTest (1 ~ 2) (new Adder [Int] {

Override def add (x: Int, y: Int): Int = Xmury

}) / / also correct, =-1

}

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