当前位置:网站首页>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
}
边栏推荐
- TCP面试
- 我想知道同花顺是炒股的么?在线开户安全么?
- 哈希表的前置知识---二叉搜索树
- flannel的host-gw与calico
- . Net, the usage of log components NLog, seriallog, log4net
- Redis cannot connect to the server through port 6379
- 科技兴关,荣联与天津海关共建基因组数据库及分析平台
- Build document editor based on slate
- 18: Chapter 3: development of pass service: 1: SMS login & registration process, introduction; (SMS verification code is used here)
- Measures to support the development of cultural and creative industries in Futian District, Shenzhen
猜你喜欢

This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel

HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 2 MPU based IOT device attack mitigation technology

Pre knowledge of hash table -- binary search tree

Flannel's host GW and calico

Black squares in word

再获认可!知道创宇入选“业务安全推进计划”首批成员单位

11、 Box styles and user interface

1、 MySQL introduction

量化初级 -- akshare获得股票代码,最简策略

有手就行的移动平均法、指数平滑法的Excel操作,用来时间序列预测
随机推荐
Introduction to the strongest swarm cluster one click deployment + hydrogen bomb level container management tool
Lintcode 130 · stacking
What determines the rent
Basic principle of MOS tube and important knowledge points of single chip microcomputer
VMware virtual machine bridging mode can not access the campus network "suggestions collection"
2、 MySQL Foundation
ctfshow web入门 命令执行web75-77
Five trends of member management in 2022
Measures to support the development of cultural and creative industries in Futian District, Shenzhen
The transformation of enterprise customers' digital assets needs to suit the case
Build document editor based on slate
关于印发《深圳市福田区支持战略性新兴产业和未来产业集群发展若干措施》的通知
leetcode 715. Range module (hard)
19: Chapter 3: develop pass service: 2: get through Alibaba cloud SMS service in the program; (it only connects with Alibaba cloud SMS server, and does not involve specific business development)
Five trends of member marketing of consumer goods enterprises in the future
In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]
介绍一下实现建模中可能用到的时间序列预测之线性二次移动平均,Excel的简单操作
I want to know whether flush is a stock market? Is online account opening safe?
杜比全景音效简介
The best CMDB system