当前位置:网站首页>Basic tutorial of scala -- 16 -- generics
Basic tutorial of scala -- 16 -- generics
2022-07-04 18:52:00 【Empty.】
Scala Basic course –16– Generic
Chapter goal
- Master generic methods , class , The use of traits
- Learn about Generic upper and lower bounds
- Understand covariance , Inversion , Unchanging usage
- Master the list to reorder cases
1. Generic
Generic means Refers to a specific data type
, stay Scala in , For generics [ data type ]
Express . In actual development , Generics are generally used in combination with arrays or collections , besides , There are three other common uses of generics :
- Generic methods
- Generic classes
- Generic characteristics
1.1 Generic methods
Generic methods refer to Define generics on method declarations , namely : The parameter type of this method is determined by generics
. When a method is called , Specify specific data types .
Format
def Method name [ Generic names ](..) = {
//...
}
demand
Define methods getMiddleElement(), Used to get the intermediate elements of an array of any type .
- Train of thought : Implement directly without considering generics ( be based on Array[Int] Realization )
- Train of thought two : Add generic support .
Reference code
// Case study : Generic method demonstration .
// details : Generic methods call methods Specify specific data types .
object ClassDemo01 {
// demand : Use a method to get the middle element of an array of any type
// Train of thought : Implement directly without considering generics ( be based on Array[Int] Realization )
//def getMiddleElement(arr: Array[Int]) = arr(arr.length / 2)
// Train of thought two : Add generic support
def getMiddleElement[T](arr: Array[T]) = arr(arr.length / 2)
def main(args: Array[String]): Unit = {
// Calling method
println(getMiddleElement(Array(1, 2, 3, 4, 5)))
println(getMiddleElement(Array("a", "b", "c")))
}
}
1.2 Generic classes
Generic classes refer to Define generics on class declarations , namely : The parameter types of members in this class are determined by generics
. When you create an object , Specify specific data types .
Format
class class [T](val Variable name : T)
demand
- Define a Pair Generic classes , This class contains two fields , And the types of the two fields are not fixed .
- Create different types of Pair Generic class object , And print .
Reference code
// Case study : Generic - Demonstrate the use of generic classes .
// Generic classes : When creating objects , Specify specific data types .
object ClassDemo02 {
//1. Achieve one Pair Generic classes
//2. Pair Class contains two fields , And the types of the two fields are not fixed
class Pair[T](var a:T, var b:T)
def main(args: Array[String]): Unit = {
//3. Create different types of generic class objects , And print
var p1 = new Pair[Int](10, 20)
println(p1.a, p1.b)
var p2 = new Pair[String]("abc", "bcd")
println(p2.a, p2.b)
}
}
1.3 Generic characteristics
Generic traits refer to Define generics on the declaration of traits , namely : The parameter types of members in this trait are determined by generics
. When defining subclasses or sub singleton objects of generic characteristics , Specify specific data types .
Format
trait Trait A[T] {
// Members of traits
}
class class B extends Trait A[ Specify the specific data type ] {
// Members in class
}
demand
- Define generic attributes Logger, This class has a variable a and show() Method , They all use Logger Generics of traits .
- Define singleton object ConsoleLogger, Inherit Logger Trait .
- Print the singleton object ConsoleLogger Members of the .
Reference code
// Case study : Demonstrate generic characteristics .
object ClassDemo03 {
//1. Define generic attributes Logger, There is one in this category a Variables and show() Method , It's all used Logger Generics of traits .
trait Logger[T] {
// Defining variables
val a:T
// Define methods .
def show(b:T) = println(b)
}
//2. Define singleton object ConsoleLogger, Inherit Logger Trait .
object ConsoleLogger extends Logger[String]{
override val a: String = " Zhang San "
}
//main Method , As the main entrance to the program .
def main(args: Array[String]): Unit = {
//3. Print the singleton object ConsoleLogger Members of the .
println(ConsoleLogger.a)
ConsoleLogger.show("10")
}
}
2. Up and down
We are using generics ( Method , class , Trait ) when , If you want to limit which class the generic type must inherit from 、 Or it must be the parent of which class . here , You need to use it Upper and lower bounds of generics
.
2.1 upper bound
Use T <: Type name
Represents adding a upper bound , Indicates that generic parameters must be derived from this class ( Or itself ) Inherit .
Format
[T <: type ]
for example : [T <: Person] It means , Generic T Data type of Must be Person Type or Person Subtypes of
demand
- Define a Person class
- Define a Student class , Inherit Person class
- Define a generic method demo(), The method receives one Array Parameters .
- limit demo Methodical Array The element type can only be Person perhaps Person Subclasses of
- Test call demo() Method , Pass in different element types Array
Reference code
// Case study : Demonstrate the upper and lower bounds of generics upper bound .
object ClassDemo04 {
//1. Define a Person class
class Person
//2. Define a Student class , Inherit Person class
class Student extends Person
//3. Define a demo Generic methods , The method receives one Array Parameters ,
// limit demo Methodical Array The element type can only be Person perhaps Person Subclasses of
def demo[T <: Person](arr: Array[T]) = println(arr)
def main(args: Array[String]): Unit = {
//4. Test call demo, Pass in different element types Array
//demo(Array(1, 2, 3)) // This will report an error , Because it can only pass in Person Or its subtype .
demo(Array(new Person()))
demo(Array(new Student()))
}
}
2.2 Lower bound
Use T >: data type
Represents adding a Lower bound , Indicates that generic parameters must be from the type itself or the parent type of the type .
Format
[T >: type ]
Be careful :
- for example : [T >: Person] It means , Generic T Data type of Must be Person Type or Person The father type of
- If a generic has an upper bound 、 There is also a lower bound . The lower bound is written before , The upper bound is written after . namely : [T >: type 1 <: type 2]
demand
- Define a Person class
- Define a Policeman class , Inherit Person class
- Define a Superman class , Inherit Policeman class
- Define a demo Generic methods , The method receives one Array Parameters ,
- limit demo Methodical Array The element type can only be Person、Policeman
- Test call demo, Pass in different element types Array
Reference code
// Case study : Demonstrate the upper and lower bounds of generics Lower bound .
// If you are setting generics , It involves the existing upper bound , There is also a lower bound , It must be : The lower bound is in front , The upper bound is behind .
object ClassDemo05 {
//1. Define a Person class
class Person
//2. Define a Policeman class , Inherit Person class
class Policeman extends Person
//3. Define a Superman class , Inherit Policeman class
class Superman extends Policeman
//4. Define a demo Generic methods , The method receives one Array Parameters ,
// limit demo Methodical Array The element type can only be Person、Policeman
// Lower bound upper bound
def demo[T >: Policeman <: Policeman](arr: Array[T]) = println(arr)
def main(args: Array[String]): Unit = {
//5. Test call demo, Pass in different element types Array
//demo(Array(new Person))
demo(Array(new Policeman))
//demo(Array(new Superman)) // Will report a mistake , Because it can only pass in : Policeman Class gets its parent type , and Superman yes Policeman Subtypes of , So no .
}
}
3. Covariance 、 Inversion 、 Non variable
stay Spark Covariance is widely used in the source code of 、 Inversion 、 Non variable , Learning this knowledge is of great significance to our future reading spark The source code is very helpful .
- Non variable : class A And the class B There is a parent-child relationship , however Pair[A] and Pair[B] Not between
Any relationship
. - Covariance : class A And the class B There is a parent-child relationship , Pair[A] and Pair[B] There are also
Father and son
Relationship . - Inversion : class A And the class B There is a parent-child relationship , however Pair[A] and Pair[B] Between
Children and parents
Relationship .
Here's the picture :
3.1 Non variable
Grammar format
class Pair[T]{
}
- The default generic class is
Immutable
- namely : type B yes A Subtypes of ,Pair[A] and Pair[B] Without any affiliation
3.2 Covariance
Grammar format
class Pair[+T]
- type B yes A Subtypes of ,Pair[B] Think of it as Pair[A] Subtypes of
- The direction of the parameterized type is consistent with that of the type .
3.3 Inversion
Grammar format
class Pair[-T]
- type B yes A Subtypes of ,Pair[A] Conversely, it can be considered as Pair[B] Subtypes of
- The direction of parameterized types is opposite to that of types
3.4 Example
demand
- Define a Super class 、 And one. Sub Class inherits from Super class
- Use covariance 、 Inversion 、 Immutable defines three generic classes
- Create generic class objects to demonstrate covariance 、 Inversion 、 Non variable
Reference code
// Case study : Demonstrate non change , Covariance , Inversion .
object ClassDemo06 {
//1. Define a Super class 、 And one. Sub Class inherits from Super class
class Super // Parent class
class Sub extends Super // Subclass
//2. Use covariance 、 Inversion 、 Immutable defines three generic classes
class Temp1[T] // Non variable
class Temp2[+T] // Covariance
class Temp3[-T] // Inversion .
def main(args: Array[String]): Unit = {
//3. Create generic classes to demonstrate covariance 、 Inversion 、 Non variable
// Demonstrate non change .
val t1:Temp1[Sub] = new Temp1[Sub]
//val t2:Temp1[Super] = t1 // Compiler error , Because non change is : Super and Sub There is a parent-child relationship , however Temp1[Super] and Temp1[Sub] There is no relationship between .
// Demonstrate covariance
val t3:Temp2[Sub] = new Temp2[Sub]
val t4:Temp2[Super] = t3 // Don't complain , Because covariance is : Super and Sub There is a parent-child relationship , therefore Temp2[Super] and Temp2[Sub] There is also a father son relationship .
//Temp2[Super] It's the father type , Temp2[Sub] It's a subtype .
// Demonstrate inverter
val t5:Temp3[Super] = new Temp3[Super]
val t6:Temp3[Sub] = t5 // Don't complain , Because inversion is : Super and Sub There is a parent-child relationship , therefore Temp3[Super] and Temp3[Sub] There is also a relationship between son and father .
//Temp3[Super] It's a subtype , Temp3[Sub] It's the father type .
}
}
4. Case study : List to reorder
4.1 demand
Known under the current project data There is one in the folder 1.txt text file , The contents of the document are as follows :
11 6 5 3 22 9 3 11 5 1 2
After reordering the above data , Re write to data Under folder 2.txt In the text file , The content is as follows :
1 2 3 5 6 9 11 22
4.2 Purpose
Investigate Generic , list , flow
Related content .
4.3 Reference code
import java.io.{
BufferedWriter, FileWriter}
import scala.io.Source
// Case study : List to reorder , And write the file .
object ClassDemo07 {
def main(args: Array[String]): Unit = {
//1. Define the data source object .
val source = Source.fromFile("./data/1.txt")
//2. Read all data from the specified file ( String form )
val list1:List[String] = source.mkString.split("\\s+").toList
//3. hold List[String] List to List[Int]
val list2:List[Int] = list1.map(_.toInt)
//4. hold List[Int] convert to Set[Int], De duplication of list elements .
val set:Set[Int] = list2.toSet
//5. hold Set[Int] Turn into List[Int], And then in ascending order
val list3:List[Int] = set.toList.sorted
//println(list3)
//6. Rewrite the data to data Under folder 2.txt In file .
val bw = new BufferedWriter(new FileWriter("./data/2.txt"))
for(i <- list3) {
bw.write(i.toString)
bw.newLine() // Don't forget to add new lines
}
//7. Release resources
bw.close()
}
}
st[Int] convert to Set[Int], De duplication of list elements .
val set:Set[Int] = list2.toSet
//5. hold Set[Int] Turn into List[Int], And then in ascending order
val list3:List[Int] = set.toList.sorted
//println(list3)
//6. Rewrite the data to data Under folder 2.txt In file .
val bw = new BufferedWriter(new FileWriter(“./data/2.txt”))
for(i <- list3) {
bw.write(i.toString)
bw.newLine() // Don't forget to add new lines
}
//7. Release resources
bw.close()
}
}
边栏推荐
- 【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
- Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
- 力扣刷题日记/day5/2022.6.27
- Five thousand words to clarify team self-organization construction | Liga wonderful talk
- Is it science or metaphysics to rename a listed company?
- My colleagues quietly told me that flying Book notification can still play like this
- File processing examples of fopen, FREAD, fwrite, fseek
- 爬虫初级学习
- How to download files using WGet and curl
- 【云端心声 建议征集】云商店焕新升级:提有效建议,赢海量码豆、华为AI音箱2!
猜你喜欢
Li Kou brush question diary /day6/6.28
力扣刷题日记/day4/6.26
How to improve development quality
Li Kou brush question diary /day8/7.1
删除二叉搜索树中的节点附图详解
1、 Introduction to C language
一、C语言入门基础
力扣刷题日记/day2/2022.6.24
Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
[mathematical modeling of graduate students in Jiangxi Province in 2022] analysis and code implementation of haze removal by nucleation of water vapor supersaturation
随机推荐
一种将Tree-LSTM的强化学习用于连接顺序选择的方法
力扣刷题日记/day5/2022.6.27
力扣刷題日記/day6/6.28
Five thousand words to clarify team self-organization construction | Liga wonderful talk
What types of Thawte wildcard SSL certificates provide
Journal des problèmes de brosse à boutons de force / day6 / 6.28
Why are some online concerts always weird?
力扣刷题日记/day7/6.30
How is the entered query SQL statement executed?
基于C语言的菜鸟驿站管理系统
Is it safe to download the mobile version of Anxin securities and open an account online
基于NCF的多模块协同实例
An example of multi module collaboration based on NCF
同事悄悄告诉我,飞书通知还能这样玩
Pb extended DLL development (super chapter) (VII)
Mysql5.7 installation tutorial graphic explanation
Wireshark抓包TLS协议栏显示版本不一致问题
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
李迟2022年6月工作生活总结
删除二叉搜索树中的节点附图详解