当前位置:网站首页>Scala-day06- pattern matching - Generic
Scala-day06- pattern matching - Generic
2022-06-26 12:09:00 【There will always be daylight】
One : Basic grammar
package chapter07
object Test01_PatternMatchBase {
def main(args: Array[String]): Unit = {
//1. Basic definition syntax
val x:Int = 2
val y:String = x match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
println(y)// according to x Value , Output y Value , This case will be output two
//2. Example : Using pattern matching to realize simple binary operation
val a = 25
val b = 13
def matchDualOp(op:Char) = op match {
case '+' => a + b
case '-' => a - b
case '*' => a * b
case '/' => a / b
case '%' => a % b
case _ => -1
}
println(matchDualOp('+'))
//3. Mode guard
// Find the absolute value of an integer
def abs(num:Int):Int = {
num match {
case i if i>= 0 => i
case i if i<0 => -i
}
}
println(abs(67))
}
}
Two : Match constants - Match type 、 Array 、 list 、 Tuples
package chapter07
object Test02_MatchTypes {
def main(args: Array[String]): Unit = {
//1. Match constants
def describeConst(x:Any):String = x match {
case 1 => "Int one"
case "hello" => "String hello"
case true => "Boolean true"
case '+' => "Char +"
case _ => ""
}
println(describeConst("hello"))
//2. Match type
def describeType(x:Any):String = x match {
case i:Int => "Int" + i
case s:String => "String" + s
case list:List[String] => "List" + list
case array:Array[Int] => "Array[Int]" + array.mkString(",")
case a => "something else:" + a
}
println(describeConst(35))
//3. The match array
for (arr <- List(
Array(0),
Array(1,0),
Array(0,1,0),
Array(1,1,0),
Array(2,3,7,15),
Array("hello",20,30)
)){
val result = arr match {
case Array(0) => "0"
case Array(1,0) => "Array(1,0)"
case Array(x,y) => "Array:" + x + "," + y
case Array(0,_*) => " With 0 The first array "
case Array(x,1,z) => " In the middle 1 A three element array of "
case _ => "something else"
}
println(result)
}
//4. Match list -- Mode one
for(list <- List(
List(0),
List(1,0),
List(0,0,0),
List(1,1,0),
List(88),
)){
val result = list match {
case List(0) => "0"
case List(x,y) => "List(x,y):" + x + "," + y
case List(0,_*) => "List(0....)"
case List(a) => "List(a):" + a
case _ => "something else"
}
println(result)
}
//4. Match list -- Mode two
val list = List(1,2,5,7,24)
val result = list match {
case first::second::rest => println(s"first:$first,second:$second,rest:$rest")
case _ => println("something else")
}
println(result)
//5. Match tuples
for(tuple <- List(
(0,1),
(0,0),
(0,1,0),
(0,1,1),
(1,23,56),
("hello",true,0.5),
)){
val result = tuple match {
case (a,b) => "" + a + "," + b
case (0,_) => "(0,_)"
case (a,1,_) => "(a,1,_)" + a
case _ => println("something else")
}
println(result)
}
}
}
package chapter07
object Test03_MatchTupleExtend {
def main(args: Array[String]): Unit = {
//1. Match... When declaring variables
val (x,y) = (10,"hello")
println(s"x:$x,y:$y")
val List(first,second,_*) = List(23,15,9,78)
val fir::sec::rest = List(23,15,9,18)
println(s"first:$fir,second:$sec,res:$rest")
//for Derivation for pattern matching
val list:List[(String,Int)] = List(("a",12),("b",35),("c",27))
for (elem <- list){
println(elem._1 + " " +elem._2)
}
// take list Elements are directly defined as tuples , Assign a value to a variable
for((word,count) <- list){
println(word + " " + count)
}
// You can ignore variables at a certain location , Just traverse key perhaps value
for((word,_) <- list){
println(word)
}
// You can specify how many values a location must have
for(("a",count) <- list){
println(count)
}
}
}3、 ... and : Matching objects and sample classes
package chapter07
object Test_MatchObject {
def main(args: Array[String]): Unit = {
val student = new Student("alice",18)
// Match the content of the object instance
val result = student match {
case Student("alice",18) => "Alice,18"
case _=> "Else"
}
println(result)
}
}
// Defining classes
class Student(val name:String,val age:Int)
// Define accompanying objects
object Student{
def apply(name: String, age: Int): Student = new Student(name, age)
// Must be realized unapply Method , Used to disassemble object properties
def unapply(student: Student): Option[(String, Int)] = {
if(student == null){
None
}else{
Some((student.name,student.age))
}
}
}
package chapter07
object Test05_MatchCaseClass {
def main(args: Array[String]): Unit = {
val student = Student("alice",18)
// Match the content of the object instance
val result = student match {
case Student("alice",18) => "Alice,18"
case _=> "Else"
}
println(result)
}
}
// Define the sample class
case class Student(val name:String,val age:Int)Four : Exception handling mechanism
package chapter08
object Test01_Exception {
def main(args: Array[String]): Unit = {
try{
val n = 10 / 0
}catch {
case e:ArithmeticException => {
println(" Arithmetic exception occurred ")
}
case e:Exception => {
println(" A general exception occurred ")
}
}finally {
println(" End of processing ")
}
}
}
5、 ... and : Implicit conversion - Implicit parameter - Implicit value - Implicit functions
package chapter08
object Test02_Implcit {
def main(args: Array[String]): Unit = {
// Implicit functions
implicit def convert(num:Int):MyRichInt = new MyRichInt(num)
println(12.myMax(15))
// Implicit class
implicit class MyRichInt(val self:Int){
// Customize the size comparison method
def myMax(n:Int):Int = if (n < self) self else n
def myMin(n:Int):Int = if (n < self) n else self
}
println(12.myMin(2))
// Implicit parameter , The same scope , There can only be one of the same type , Implicit values override default values
implicit val str:String = "alice"
def sayHello(implicit name:String):Unit ={
println("hello," + name)
}
sayHello
}
}
/*
// Custom class
class MyRichInt(val self:Int){
// Customize the size comparison method
def myMax(n:Int):Int = if (n < self) self else n
def myMin(n:Int):Int = if (n < self) n else self
}*/
6、 ... and : Generic - Covariant and contravariant
package chapter08
object Test03_Generics {
def main(args: Array[String]): Unit = {
// Covariant and contravariant
val child:Parent = new Child
val childList:MyCollecion[Parent] = new MyCollecion[Child]
}
}
// Define inheritance
class Parent{}
class Child extends Parent{}
class SubChild extends Child{}
// Define collection types for generics
class MyCollecion[E]{}

7、 ... and : Upper and lower bounds of generics
Class PersonList[T<:Person]{ // The upper limit of generics
}
Class PersonList[T>:Person]{ // The lower bound of generics
}
边栏推荐
- Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source
- How to calculate flops and params in deep learning
- 2016年四川省TI杯电子设计竞赛B题
- Precautions for opening a securities account is it safe to open an account
- Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open a mobile account?
- Matlab programming example: how to count the number of elements in a cell array
- Build document editor based on slate
- Ctfshow web getting started command execution web75-77
- 房租是由什么决定的
- Redis cannot connect to the server through port 6379
猜你喜欢

Excel operation of manual moving average method and exponential smoothing method for time series prediction
![Compréhension approfondie de l'expérience de port série stm32 (registre) [Tutoriel de niveau nounou]](/img/b2/f09e220918a85b14a1993aa85f7720.png)
Compréhension approfondie de l'expérience de port série stm32 (registre) [Tutoriel de niveau nounou]

APICloud 实现文档下载和预览功能

Black squares in word

有手就行的移动平均法、指数平滑法的Excel操作,用来时间序列预测

11、 Box styles and user interface

FasterRCNN

Loggie encoding and newline character test

介紹一下實現建模中可能用到的時間序列預測之線性二次移動平均,Excel的簡單操作
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d2/a6cbb0abe9e04c412d1f6021430528.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
随机推荐
统计遗传学:第一章,基因组基础概念
Omni channel member link - tmall member link 3: preparation of member operation content
Oracle锁表查询和解锁方法
量化初级 -- akshare获得股票代码,最简策略
我想知道同花顺是炒股的么?手机开户安全么?
Pratique de l'attaque et de la défense du réseau HUST | 6 Expérience de sécurité du microprogramme de l'équipement IOT | expérience 2 technologie d'atténuation des attaques de l'équipement IOT basée s
File decryption in webgame development
Refined operation, extending the full life cycle value LTV
基于slate构建文档编辑器
I want to know whether flush is a stock market? Is it safe to open a mobile account?
我想知道,股票开户有哪些优惠活动?网上开户是否安全么?
HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 2 MPU based IOT device attack mitigation technology
Dynamic programming to solve stock problems (Part 2)
Jsonarray and jsonobject of fastjson [easy to understand]
APICloud 实现文档下载和预览功能
Basic principle of MOS tube and important knowledge points of single chip microcomputer
What determines the rent
leetcode 715. Range 模块 (hard)
科技兴关,荣联与天津海关共建基因组数据库及分析平台
十大券商有哪些?手机开户安全么?