当前位置:网站首页>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())
}
}
边栏推荐
- uni-app与uviewUI实现仿小米商城app(附源码)
- Li Kou brush question diary /day2/2022.6.24
- Five thousand words to clarify team self-organization construction | Liga wonderful talk
- Li Kou brush question diary /day7/2022.6.29
- Halcon模板匹配
- The money circle boss, who is richer than Li Ka Shing, has just bought a building in Saudi Arabia
- 中国农科院基因组所汪鸿儒课题组诚邀加入
- 删除二叉搜索树中的节点附图详解
- Tutorial on the use of Huawei cloud modelarts (with detailed illustrations)
- People in the workplace with a miserable expression
猜你喜欢

Thawte通配符SSL证书提供的类型有哪些

基于C语言的菜鸟驿站管理系统

My colleagues quietly told me that flying Book notification can still play like this

Li Kou brush question diary /day6/6.28

Halcon template matching

Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii

机器学习概念漂移检测方法(Aporia)

爬虫初级学习

【2022年江西省研究生数学建模】水汽过饱和的核化除霾 思路分析及代码实现
![[cloud native] what is the](/img/00/0cb0f38bf3eb5dad02b3bc4ead36ba.jpg)
[cloud native] what is the "grid" of service grid?
随机推荐
一种将Tree-LSTM的强化学习用于连接顺序选择的方法
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
Is it science or metaphysics to rename a listed company?
Imitation of numpy 2
Thawte通配符SSL证书提供的类型有哪些
【210】PHP 定界符的用法
Mxnet implementation of googlenet (parallel connection network)
Blue bridge: sympodial plant
I wrote a learning and practice tutorial for beginners!
基于C语言的菜鸟驿站管理系统
网上开户安全吗?是真的吗?
fopen、fread、fwrite、fseek 的文件处理示例
. Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines
爬虫(6) - 网页数据解析(2) | BeautifulSoup4在爬虫中的使用
Five thousand words to clarify team self-organization construction | Liga wonderful talk
Mysql5.7 installation tutorial graphic explanation
Li Kou brush question diary /day7/2022.6.29
Grain Mall (I)
Scala基础教程--19--Actor