Scala类与模式匹配

时间:2022-09-09 08:36:43

Scala 官网:http://www.scala-lang.org/

一、类

1、main

/*
* main method
* ⑴如同Java中,如果要运行一个程序,必须编写一个包含main方法的类一样;
* 在Scala中,如果要运行一个应用程序,必须要有一个main方法,作为入口;
* ⑵在Scala中的main方法定义为def main(args:Array[String]),而且必须定义在object中;
* ⑶运行下面的代码,需要将其放入.scala文件中,然后先使用scalac编译,再用scala执行;
*/
object HelloWorld {
def main(args: Array[String]) {
println("Hello World!!!")
}
}
Scala类与模式匹配

2、object

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/*
* class and object
* ⑴object相当于class的单个实例,通常在里面放一些静态的field或者method;
* ⑵第一次调用object的方法时,就会执行object的constructor,也就是object内部不在method中的代码;
* 但是object不能定义接受参数的constructor;
* ⑶object的constructor只会在其第一次被调用时执行一次,以后再次调用就不会再次执行constructor了;
* ⑷object通常用于作为单例模式的实现,或者放class的静态成员,比如工具方法;
* ⑸如果有一个class,还有一个与class同名的object,那么就称这个object是class的伴生对象,
* class是object的伴生类;
* ⑹伴生类和伴生对象必须存放在一个.scala文件之中;
* ⑺伴生类和伴生对象,最大的特点就在于,相互可以访问private field;
*/
object Person {
private val eyeNum = 2
println("this is Person object!")
def getEyeNum = eyeNum

def main(args: Array[String]) {
val person = new Person("hadoop",11)
person.sayHello
}
}

//当函数没有参数时可以省略小括号,当函数体只有一句话时,可以省略花括号
class Person(val name:String, val age:Int){
def sayHello = println("Hi, "
+ name
+ ", I guess you are "
+ age
+ " years old!"
+ ", and usually you must have "
+ Person.eyeNum
+ " eyes.")
}
Scala类与模式匹配

3、apply

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴通常我们在伴生对象中定义apply方法,在方法中实现构造伴生类实例的功能;
* ⑵apply方法的方法名称必须使用apply;
* ⑶apply方法的参数接受与class类主构造方法相同的参数,并返回该类的实例;
*/
class person1 {
//定义属性
var name: String = ""

//定义方法
def wachTV(TVName: String) = {
println(name + " is waching " + TVName + " with " + person1.eyeNm + " eyes ") //可以调用其伴生对象的私有属性
}
}

object person1 extends App {
def apply() = {
println("****apply function has been invoked!!*******")
new person1()
}

private val eyeNm: Int = 2
val p =person1()
p.name = "Lili"
p.wachTV("DongFang")
}
Scala类与模式匹配

4、this

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴主构造器直接跟在类名后面,主构造器中的参数最后会被变异成字段、属性;
* ⑵主构造器执行时,会执行类中的所有语句;
* ⑶假设参数声明时不带val或var,那么相当于private[this],只能在内部使用;
* @param name
* @param age
*/
class Person2(var name: String, val age: Int) {
//constructor
val school: String = "bruce"
var sex: String = ""
//附属构造器名称为this;
def this(name: String, age: Int, sex: String) = {
this(name, age)
this.sex = sex
}
}

object Person2 extends App {
//调用主构造器
val person = new Person2("tom", 21)
println("name:" + person.name + ",age:" + person.age + ",school:" + person.school)
//调用附属构造器
var person1=new Person2("mary",22,"male")
println("name:" + person1.name + ",age:" + person1.age + ",school:" + person1.school+",sex:"+person1.sex)
}
Scala类与模式匹配

5、exception

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* Scala异常处理:case匹配的方式处理(处理或者throw出去)
*/
object exception extends App{

try {
val a = 1 / 0
}
catch {
case e: ArithmeticException => throw new RuntimeException("除数不能为0") //匹配除数为零
case _ => println("other.......") //匹配其他异常
}
}
Scala类与模式匹配

二、模式匹配

1、模式匹配-值

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴Scala是没有Java中的switch case语法的,相对应的,Scala提供了更强大的match case语法,即模式匹配;
* ⑵Scala的match case与Java的switch case最大的不同点在于,Java的switch case仅能匹配变量的值,比如1,2,a,b等;
* 而Scala的match case可以匹配各种情况,比如变量的类型、集合的元素、有值或无值;
* ⑶match case的语法如下:变量 match {case 值 => 代码}。如果值为下划线,则代表了不满足以上所有情况下的默认情况如何处理;
* 此外,match case中,只要一个case分支满足并处理了,就不会继续判断下一个case分支了。(与Java不同,Java的switch case需要用break阻止);
* ⑷当然,match case语法最基本的应用,就是对变量的值进行模式匹配;
*/
object grade1 extends App {
def judgeGrade(grade:String){
grade match {
case "A" => println("Excellent")
case "B" => println("Good")
case "C" => println("Just so so")
case _ => println("You need work harder")
}
}
judgeGrade("D")
}
Scala类与模式匹配

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴Scala的模式匹配语法,有一个特点在于,可以在case后的条件判断中,不仅仅只是提供一个值,
* 而是可以在值后面再加一个if守卫,进行双重过滤;
* ⑵Scala的模式匹配语法,可以将模式匹配的默认情况下划线,替换为一个变量名,
* 此时模式匹配语法就会把将要匹配的值赋值给这个变量,从而可以在后面的处理语句中使用要匹配的值;
*/
object grade2 extends App{
def judgeGrade(name:String, grade:String){
grade match {
case "A" => println(name+ ",you are excellent")
case "B" => println(name+ ",you are good")
case "C" => println(name+ ",you are just so so")
case _grade if name == "bruce" => println(name+", your grade is "+ _grade)
case _grade => println("You need work harder,your grade is "+ _grade)
}
}
judgeGrade("bruce","D")
}
Scala类与模式匹配

2、模式匹配-类型

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴Scala的模式匹配一个强大之处就在于,可以直接匹配类型,而不是值!!!
* ⑵对类型如何进行匹配?其他语法与匹配值其实是一样的,但是匹配类型的话,就是要用
* case 变量:类型 => 代码
*/
object matchType extends App{
def judgeType(x:Any)={
x match {
case x:Int => println("Int........")
case x:String => println("String........")
case x:Double => println("Double........")
case _ => println("other........")
}
}
judgeType("aa")
}
Scala类与模式匹配

3、模式匹配-array、list

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴对Array进行模式匹配,分别可以匹配带有指定元素的数组、带有指定个数元素的数组、以某元素打头的数组;
* ⑵对List进行模式匹配,与Array类似,但是需要使用List特有的::操作符;
*/
object matchArray extends App{
def greeting(arr: Array[String]) = {
arr match {
case Array("Hadoop") => println("hi ,Hadoop !") //匹配带有指定元素的数组
case Array("Hadoop",_*)=>println("hi,Hadoop,please introduce your friends to me ")//以某元素打头的数组
case Array(a,b,c) => println(a+","+b+","+c+",there are 3 students !!") //带有指定个数元素的数组
case _ => println("other........")
}
}

def greet(list: List[String]) = {
list match {
case "Hadoop"::Nil => println("hi ,Hadoop !") //匹配带有指定元素的数组
case "Hadoop"::tail => println("hi,Hadoop,please introduce your friends to me ") //以某元素打头的数组
case a::b::c::Nil => println(a + "," + b + "," + c + ",there are 3 students !!") //带有指定个数元素的数组
case _ => println("other........")
}
}
greeting(Array("Hive","Hadoop","Scala"))
println("*********************************************")
greet(List("Hive","Hadoop","Scala"))
}

Scala类与模式匹配

4、模式匹配-tuple

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* 对tuple元组的元素情况匹配
*/
object matchTuple extends App{
def match_tuple(tuple:Any) ={
tuple match {
case (0,_) => println("the first is 0")
case (a,0,_) => println("the second is 0 "+a)
case _ => println("other.....")
}
}

match_tuple(0,"Scala")
match_tuple(2,0,1)
match_tuple((0,0,3))
}
Scala类与模式匹配

5、模式匹配-class

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴Scala中提供了一种特殊的类,用case class进行声明,中文也可以称作样例类;
* case class其实有点类似于Java中的JavaBean的概念;
* 即只定义field,并且由Scala编译时自动提供getter和setter方法,但是没有method;
* ⑵case class的主构造函数接收的参数通常不需要使用var或val修饰,Scala自动就会使用val修饰;
* Scala自动为case class定义了伴生对象,也就是object,并且定义了apply()方法,
* 该方法接收主构造函数中相同的参数,并返回case class对象;
*/
case class Teacher(name: String, subject: String)
case class Student(name: String, classRoom: String)
class PP()
class matchClass{
def judgeID(p: Any) = {
p match {
case Teacher(name, subject) => println("name:" + name + ",subject:" + subject)
case Student(name, classRoom) => println("name:" + name + ",classRoom:" + classRoom)
case _ => println("who are you !!")
}
}
}
object matchClass extends App{
val p = new matchClass
p.judgeID(new PP())
p.judgeID(Teacher("bruce","Scala")) //因为我们声明的Teacher为case class类,所以不需要使用new
}

Scala类与模式匹配

6、模式匹配-option

package com.example.scala

/**
* Created by Bruce on 2017/6/12.
*/
/**
* ⑴Scala有一种特殊的类型,叫做Option,Option有两种值,一种是Some,表示有值,一种是None,表示没有值;
* ⑵Option通常会用于模式匹配中,用于判断某个变量是否有值,比null更加简洁明了;
* ⑶Spark源码中大量的使用了Option,比如Some(a)、None这种语法,因此看得懂Option模式匹配,才能够读懂spark源码;
*/
object matchOption extends App{

val grades=Map("Scala"->"A","Hadoop"->"C","Spark"->"B")

def getGrade(name:String)={
val grade=grades.get(name)
grade match {
case Some(grade1)=>println("your grade is "+ grade1)
case None =>println("your grade is not in this system!")
}
}
getGrade("Spark")
}
Scala类与模式匹配