当前位置:网站首页>Scala basic tutorial -- 14 -- implicit conversion
Scala basic tutorial -- 14 -- implicit conversion
2022-07-04 18:52:00 【Empty.】
Scala Basic course –14– Implicit conversion
Chapter goal
- Master the relevant content of implicit conversion
- Master the relevant contents of implicit parameters
- Master getting the average of list elements
1. Introduction to implicit conversion and implicit parameters
Implicit conversions and implicit parameters are Scala It's a very distinctive feature of , It's also Java And other programming languages do not have the function . We can easily use implicit transformation to enrich the functions of existing classes . In the subsequent writing Akka Concurrent programming , Spark, Flink They are often used in programs .
Implicit conversion : It means using implicit keyword Declared with Single parameter Methods .
Implicit parameter : It means using implicit keyword Decorated variable .
Be careful :
implicit keywordIs in Scala Of 2.10 Version of .
2. Implicit conversion
2.1 summary
Implicit transformation , Refer to With implicit Keyword declared method with a single parameter . This method is called automatically , Used to implement Automatically convert one type of data into another type of data .
2.2 Use steps
- stay
object Singleton objectDefine implicit conversion methods in .
The implicit transformation method explains : Just use implicit Methods of keyword modification .
- Where implicit conversion is required , Introduce implicit transformation .
Be similar to
Guide pack, adoptimportKeyword implementation .
- When you need to use
Implicit conversion methodwhen , The program will automatically call
2.3 Example 1 : Manually import implicit conversion methods
demand
By implicit transformation , Give Way File The objects of class have read function ( namely : The content in the text is read out in the form of string ).
step
- establish RichFile class , Provide a read Method , Used to read the contents of the file as a string
- Define an implicit conversion method , take File Implicitly convert to RichFile object
- Create a File Class object , Import implicit transformation , call File Of read Method .
Reference code
import java.io.File
import scala.io.Source
// Case study : demonstration Implicit conversion , Manual import .
/* Implicit conversion : summary : use implicit Embellished Method with single parameter , This method is called automatically . // Premise : Need to manually introduce . effect : Used to enrich the functions of some objects . Big white explanation : An object does not have a function , Let him have this function by specific means . // Simple understanding : This is similar to Java Decoration design pattern in . //BufferedReader br = new BufferedReader(new FileReader("a.txt)) // This will give you an error , A must be passed in To be upgraded object . //BufferedReader br = new BufferedReader("a.txt") */
object ClassDemo01 {
//1. Define a RichFile class , Used for ordinary File Object to add read() function .
class RichFile(file:File) {
// Define a read() Method , Used to read data .
def read() = Source.fromFile(file).mkString
}
//2. Define a singleton object , Contains a method , This method is used for : ordinary File object convert to RichFile object .
object ImplicitDemo {
// Define a method , This method is used for : ordinary File object convert to RichFile object .
implicit def file2RichFile(file:File) = new RichFile(file)
}
def main(args: Array[String]): Unit = {
//3. A very, very important place : Manual import Implicit conversion .
import ImplicitDemo.file2RichFile
//4. Create a normal File object , Try calling its read() function .
val file = new File("./data/1.txt")
/* Execute the process : 1. Look for the File Is there a class read(), Use it if you have it . 2. If not, go to , Check whether there is implicit conversion of this type , Turn this object into another object . 3. If there is no implicit conversion , Direct error . 4. If you can upgrade this object to another object , Then check whether the method is specified in the upgraded object , Yes , Don't complain , If not, report wrong . The following case implementation process : 1. file No in object read() Method . 2. Yes detected Implicit transformation will file object Turn into RichFile object . 3. call RichFile Object's read() Method , Print the results . */
println(file.read())
}
}
2.4 The timing of implicit conversion
since Implicit conversion So easy to use , When will the program Automatically call implicit conversion methods Well ?
- When an object calls a method or member that does not exist in the class , The compiler will automatically implicitly convert the object
- When the parameter type in the method is inconsistent with the target type , The compiler will also automatically call implicit conversion .
2.5 Example 2 : Automatically import implicit conversion methods
stay Scala in , If There are implicit conversion methods in the current scope , The implicit conversion is automatically imported .
demand : Define the implicit conversion method in main Where object Singleton object in
import java.io.File
import scala.io.Source
// demonstration Implicit conversion , Automatic import .
object ClassDemo02 {
//1. Define a RichFile class , Define one inside read() Method .
class RichFile(file:File) {
def read() = Source.fromFile(file).mkString
}
def main(args: Array[String]): Unit = {
//2. Customize a method , This method uses implicit modification ,
// Used to put : ordinary File -> RichFile, When the program needs to be used , Automatically called .
implicit def file2RichFile(file:File) = new RichFile(file)
//3. establish File object , call read() Method .
val file = new File("./data/2.txt")
println(file.read())
}
}
3. Implicit parameter
stay Scala The methods of , You can bring one Marked as implicit Parameter list for . When the method is called , This parameter list does not need to be initialized , because The compiler will automatically find the default value , Provided to the method .
3.1 Use steps
- Add a parameter list after the method , Parameters use implicit modification
- stay object In the definition of implicit Decorated implicit values
- Calling method , You don't have to pass in implicit Decorated parameter list , The compiler will automatically find the default value
Be careful :
- Like implicit conversions , have access to import Import implicit parameters manually
- If an implicit value is defined in the current scope , It will be imported automatically
3.2 Example
demand
- Define a show Method , Implement the value to be passed in , Wrap it with the specified prefix separator and suffix separator .
for example : show(“ Zhang San ”)(“<<<”, “>>>”), Then the running result is : <<< Zhang San >>>
- Use implicit parameters to define delimiters .
- Call the method , And print the results .
Reference code
- Mode one : Manually import hidden
// Case study : Demonstrate implicit parameters , Manual import .
// Presentation parameters : If a parameter list of a method uses implicit Modify the , Then the parameter list is : Implicit parameter .
// benefits : When we call the method again , About implicit parameters, you can call the default value , We don't need to pass in parameters .
object ClassDemo03 {
// demand : Define a method , Pass in a name , Then wrap the name with the specified prefix and suffix .
//1. Define a method show(), Receive a name , Accepting a prefix , Suffix information ( This is an implicit parameter ).
def show(name:String)(implicit delimit:(String, String)) = delimit._1 + name +
delimit._2
//2. Define a singleton object , Set default values for implicit parameters .
object ImplicitParam {
implicit val delimit_defalut = "<<<" -> ">>>"
}
def main(args: Array[String]): Unit = {
//3. Manual import : Implicit parameter .
import ImplicitParam.delimit_defalut
//4. Try calling show() Method .
println(show(" Zhang San "))
println(show(" Zhang San ")("(((" -> ")))"))
}
}
- Mode two : Automatically import implicit parameters
// Case study : Demonstrate implicit parameters , Automatic import .
// Presentation parameters : If a parameter list of a method uses implicit Modify the , Then the parameter list is : Implicit parameter .
// benefits : When we call the method again , About implicit parameters, you can call the default value , We don't need to pass in parameters .
object ClassDemo04 {
// demand : Define a method , Pass in a name , Then wrap the name with the specified prefix and suffix .
//1. Define a method show(), Receive a name , Accepting a prefix , Suffix information ( This is an implicit parameter ).
def show(name:String)(implicit delimit:(String, String)) = delimit._1 + name +
delimit._2
def main(args: Array[String]): Unit = {
//2. Automatic import Implicit parameter .
implicit val delimit_defalut = "<<<" -> ">>>"
//3. Try calling show() Method .
println(show(" Li Si "))
println(show(" Li Si ")("(((" -> ")))"))
}
}
4. Case study : Get the average value of list elements
demand
By implicit transformation , Get the average value of all elements in the list .
Purpose
Investigate Implicit conversion , list Related content .
step
- Define a
RichListclass , Used for ordinaryListadd toavg()Method , Used to get the average value of list elements . - Definition
avg()Method , Used to obtainListThe average value of all elements in the list . - Define implicit conversion methods , Used to convert ordinary
ListObject toRichListobject . - Definition
Listlist , Get the average value of all elements .
Reference code
object ClassDemo05 {
//1. Define a RichList class , Used for ordinary List add to avg() Method .
class RichList(list:List[Int]) {
//2. Definition avg() Method , Used to obtain List The average value of all elements in the list .
def avg() = {
if(list.size == 0) None
else Some(list.sum / list.size)
}
}
//main Method , As the main entrance to the program .
def main(args: Array[String]): Unit = {
//3. Define implicit conversion methods .
implicit def list2RichList(list:List[Int]) = new RichList(list)
//4. Definition List list , Get the average value of all elements .
val list1 = List(1, 2, 5, 4, 3)
println(list1.avg())
}
}
边栏推荐
猜你喜欢

华为云ModelArts的使用教程(附详细图解)

ISO27001认证办理流程及2022年补贴政策汇总

Li Kou brush question diary /day7/2022.6.29

People in the workplace with a miserable expression

Load test practice of pingcode performance test

输入的查询SQL语句,是如何执行的?

删除二叉搜索树中的节点附图详解

Digital "new" operation and maintenance of energy industry

Journal des problèmes de brosse à boutons de force / day6 / 6.28

TCP两次挥手,你见过吗?那四次握手呢?
随机推荐
Is it safe to download the mobile version of Anxin securities and open an account online
力扣刷题日记/day5/2022.6.27
Thawte通配符SSL证书提供的类型有哪些
The controversial line of energy replenishment: will fast charging lead to reunification?
[211] go handles the detailed documents of Excel library
2022年DCMM认证全国各地补贴政策汇总
输入的查询SQL语句,是如何执行的?
Deleting nodes in binary search tree
力扣刷题日记/day6/6.28
Li Kou brush question diary /day5/2022.6.27
Android uses sqliteopenhelper to flash back
Scala基础教程--15--递归
Scala基础教程--14--隐式转换
[210] usage of PHP delimiter
同事悄悄告诉我,飞书通知还能这样玩
[go ~ 0 to 1] read, write and create files on the sixth day
[cloud native] what is the "grid" of service grid?
How to improve development quality
How to download files using WGet and curl
[cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!