当前位置:网站首页>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
}
边栏推荐
- I want to know whether flush is a stock market? Is it safe to open a mobile account?
- 介绍一下实现建模中可能用到的时间序列预测之线性二次移动平均,Excel的简单操作
- The loss of female scientists
- Lintcode 130 · 堆化
- 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)
- The best CMDB system
- Matlab programming example: how to count the number of elements in a cell array
- Redis的最佳实践?看完不心动,算我输!!
- I want to know how the top ten securities firms open accounts? Is online account opening safe?
猜你喜欢
深度理解STM32的串口實驗(寄存器)【保姆級教程】
Redis best practices? If I don't feel excited after reading it, I will lose!!
JMeter response time and TPS listener tutorial
This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
19:第三章:开发通行证服务:2:在程序中,打通阿里云短信服务;(仅仅是打通阿里云短信服务器,不涉及具体的业务开发)
Cet article présente la moyenne mobile quadratique linéaire et le fonctionnement simple d'Excel pour réaliser la prédiction des séries chronologiques dans la modélisation.
Statistical genetics: Chapter 2, the concept of statistical analysis
leetcode 715. Range 模块 (hard)
FastRCNN
International beauty industry giants bet on China
随机推荐
FasterRCNN
MOS管基本原理,单片机重要知识点
Assembly language (7) operation instruction
Ctfshow web getting started command execution web75-77
The best CMDB system
【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
基于slate构建文档编辑器
Deep thinking from senior member managers
利用 Repository 中的方法解决实际问题
The most complete kubernetes core command of the latest version so far
MQTT断开重连
webgame开发中的文件解密
How to do well in member marketing three steps to teach you to understand member management
Measures to support the development of cultural and creative industries in Futian District, Shenzhen
Build document editor based on slate
In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]
Re recognized! Know that Chuangyu has been selected as one of the first member units of the "business security promotion plan"
Basic use of express in nodejs
初探Protostuff的使用[通俗易懂]
UDP协议详解[通俗易懂]