当前位置:网站首页>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 keyword
Is 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 object
Define 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
, adoptimport
Keyword implementation .
- When you need to use
Implicit conversion method
when , 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
RichList
class , Used for ordinaryList
add toavg()
Method , Used to get the average value of list elements . - Definition
avg()
Method , Used to obtainList
The average value of all elements in the list . - Define implicit conversion methods , Used to convert ordinary
List
Object toRichList
object . - Definition
List
list , 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())
}
}
边栏推荐
- 力扣刷題日記/day6/6.28
- 【云端心声 建议征集】云商店焕新升级:提有效建议,赢海量码豆、华为AI音箱2!
- DB engines database ranking in July 2022: Microsoft SQL Server rose sharply, Oracle fell sharply
- 力扣刷题日记/day2/2022.6.24
- 【2022年江西省研究生数学建模】水汽过饱和的核化除霾 思路分析及代码实现
- Principle and application of ThreadLocal
- TCP两次挥手,你见过吗?那四次握手呢?
- 如何使用 wget 和 curl 下载文件
- 激进技术派 vs 项目保守派的微服务架构之争
- 一种将Tree-LSTM的强化学习用于连接顺序选择的方法
猜你喜欢
The controversial line of energy replenishment: will fast charging lead to reunification?
2022年全国CMMI认证补贴政策|昌旭咨询
基于C语言的菜鸟驿站管理系统
Scala基础教程--13--函数进阶
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
vbs或vbe如何修改图标
Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
Imitation of numpy 2
.NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
蓝桥:合根植物
随机推荐
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
Scala基础教程--13--函数进阶
I wrote a learning and practice tutorial for beginners!
力扣刷题日记/day4/6.26
基于C语言的菜鸟驿站管理系统
力扣刷题日记/day7/2022.6.29
How to modify icons in VBS or VBE
华为云ModelArts的使用教程(附详细图解)
字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
基于NCF的多模块协同实例
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
.NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
ESP32-C3入门教程 问题篇⑫——undefined reference to rom_temp_to_power, in function phy_get_romfunc_addr
[HCIA continuous update] WAN technology
. Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
[go language question brushing chapter] go conclusion chapter | introduction to functions, structures, interfaces, and errors
ITSS运维能力成熟度分级详解|一文搞清ITSS证书
力扣刷题日记/day8/7.1
Numpy 的仿制 2
Halcon template matching