当前位置:网站首页>Explanation and practice of implicit transformation and implicit parameters in Scala
Explanation and practice of implicit transformation and implicit parameters in Scala
2022-06-12 23:43:00 【Hua Weiyun】
brief introduction :
Scala Implicit conversion and implicit parameter function provided by , It's a very distinctive function . yes Java And other functions that programming languages don't have . It allows you to manually specify to convert objects of one type to objects of other types , Or add a method to a class . Through these functions , Can achieve very powerful functions .
1、 Implicit conversion
The core of implicit transformation is to define a usage implicit Methods of keyword modification , The implementation converts an original class into a target class , So you can call methods in the target class , Is it powerful . The method of implicit transformation needs to be defined in a object in .
Example 1 : Transform the third-party library class , Give Way File Class owned RichFile Class read Method
import java.io.Fileimport scala.io.Sourceobject ExecFileDef { // Define a method of implicit transformation , Realize the File convert to RichFile implicit def file2RichFile(file: File) = new RichFile(file)}// Expand file class class RichFile(val file: File){ // Method of reading data file def read():String={ Source.fromFile(file).mkString }}object RichFile{ def main(args: Array[String]): Unit = { //1、 Construct a File object val file = new File("F:\\acc.txt") //2、 Manually import implicit conversions import ExecFileDef.file2RichFile // At this time file Has been transformed , have access to read Method val data: String = file.read println(data) }}Example 2 : Use implicit conversions for classes you define , Ordinary people become big men
class AveragePerson(val name: String)class Mogul(val name: String) { def come(): Unit = { println(" bosses "+ name + " coming , Applause reminds me of , Bring your own halo , Crazy money !") }}object TransformExec { implicit def AveragePerson2Mogul(averagePerson: AveragePerson): Mogul = { new Mogul(averagePerson.name) } def main(args: Array[String]): Unit = { val mogul = new AveragePerson(" Orange garden ") mogul.come() }} result :
Example 3 : A class implicitly converts a class with the same method
class Aclass B(a: A) { def readBook(): Unit ={ println("B read ") }}class C(a: A){ def readBook(): Unit ={ println("C read ") } def writeBook(): Unit ={ println("C To write a book ") }}object BC{ // Create a class to convert to 2 Implicit conversion of classes implicit def A2B(a: A)=new B(a) implicit def A2C(a: A)=new C(a)}object C{ def main(args: Array[String]) { // Guide pack //import BC._ This will AB All implicit transformations under the class are imported //import BC.A2B Import only A Class to B Class //import BC.A2C Import only A Class to C Class import BC._ val a = new A // because B Class and C Classes have readBook(), Only one of them can be imported , Otherwise, the code will report an error when calling a common method //a.readBook() //A Class can execute C Class writeBook() a.writeBook() }} result :
2、 Implicit parameter
It means in a function or method , Define a with implicit Modified parameters , here Scala Will try to find a specified type of implicit Modified parameters , That is, the implicit value , And injection parameters . Implicit parameters also need to be defined in a object in .
Example : Use of implicit parameters , The boss gives money to his employees
object Company{ // Be careful : Implicit values of the same type are allowed only once , Otherwise, an error will be reported implicit val name: String = " Orange garden " implicit val salary: Double = 100000.0 // If it occurs again, an error will be reported //implicit val zzz: String=" Orange ape "}class Boss { // Define a with implicit The decorated parameter type is String // Note the type of parameter matching , What it needs is String Implicit value of type def callName(implicit name: String): String={ name } // Define a with implicit Modified parameters , The type is Double // Note the type of parameter matching , What it needs is Double Implicit value of type def getMoney(implicit money: Double): String={ money.toString }}object Boss extends App{ // Use import Import defined implicit values , Be careful : It must be loaded first, or an error will be reported import Company.name import Company.salary val boss = new Boss println(boss.callName + ":" + boss.getMoney)} result :
边栏推荐
- Mgr and greatsql resource summary
- 2022年危险化学品经营单位安全管理人员考试试题及在线模拟考试
- Record 5 - the serial port of stm32f411ceu6 realizes the sending and receiving of fixed length data and variable length data
- Detr (detection with transformers) learning notes
- [opencv learning] small ticket recognition based on perspective transformation and OCR recognition
- KConfig
- How to get Matplotlib figure size
- Industry reshuffle, a large number of programmers are going to lose their jobs? How can we break the current workplace dilemma
- 2022年G3锅炉水处理考题模拟考试平台操作
- Face detection: mtcnn
猜你喜欢

度量学习(Metric Learning)【AMSoftmax、Arcface】

How does idea switch the interface to Chinese

Alien skin exposure X7 color filter plug-in, raw post-processing tool

2202 resume making

Redis实现短信验证码登录

2202 - production de CV

Enterprise wechat H5_ Authentication, PC website, enterprise wechat scanning code, authorized login
![[redis sentinel] failed listening on port 26379 (TCP) & sentinel mode no response problem solved](/img/0e/d734cd835d44361d6d93cc1be81c98.jpg)
[redis sentinel] failed listening on port 26379 (TCP) & sentinel mode no response problem solved

Operation of simulation test platform for G3 boiler water treatment test questions in 2022

H5时代leaflet中还在用DivIcon?
随机推荐
Design MySQL table structure for message queue to store information data
InfoQ geek media's 15th anniversary solicitation | brief introduction to the four challenges of building a micro service architecture
1111111111111111111111111111111111111111111111111111111
应用最广泛的动态路由协议:OSPF
Lower interest rates lead to higher bond prices
2022 R2 mobile pressure vessel filling test questions and online simulation test
Don't write about the full screen explosion, try the decorator mode, this is the elegant way!!
Zhengzhou University of light industry -- development and sharing of harmonyos pet health system
Chapter 8 - shared model JUC
Leetcode 2200. Find all k nearest neighbor subscripts in the array (yes, one pass)
KConfig
Printf segment error (core dump): a problem caused by formatted output
Alien Skin Exposure X7调色滤镜插件,RAW后期处理工具
PostgreSQL 中文社区黑龙江分会和辽宁分会成立啦!
PyTorch常用参数初始化方法:【均匀分布、正态(高斯)分布、Xavier、kaiming、正交矩阵、稀疏矩阵、常数、单位矩阵、零填充】
度量学习(Metric Learning)【AMSoftmax、Arcface】
Modify the text color of the menu on the right of toobar
SAP 业务技术平台(BTP) 上的 Business Rules Service 使用介绍
It is meaningful to define genus, and D can use it to explain semantics
Alien skin exposure X7 color filter plug-in, raw post-processing tool