一、模式匹配
模式匹配就是java里的switch,是一种分支结构,在scala里,支持数组,集合,还有类型
与java不同,match没有匹配到会抛出异常
Exception in thread "main" scala.MatchError
1.基本语法
scala
var person = "ETO"
person match{
case "ETO" =>{
print("Hello,ETO")
}
case "Eployee"=>{
print("Hello,Eployee")
}
case _ =>{
print("Hello,other")
}
}
java
String person = "ETO";
switch(person){
case "ETO" :
System.out.print("Hello,ETO")
break;
case "Eployee":
System.out.print("Hello,Eployee")
break;
default:
System.out.print("Hello,other")
}
如果person等于其中某个case的话就会执行哪个代码块。从上至下判断,若判断进入了一个case块便不会再执行其他代码块。
2.加条件的匹配
var person = "ETO"
var isReady = false;
person match{
case "ETO" if(isReady)=>{
print("Hello,ETO")
}
case "Eployee"=>{
print("Hello,Eployee")
}
case _ =>{
print("Hello,other")
}
}
只有条件符合才能执行该块代码,就如同用if包裹整个case
3.Array匹配
var arr = Array("zhangsan","lisi")
arr match{
case Array("zhangsan","lisi") =>{
arr.foreach(print)
}
case Array("zhangsan",_*) => {
arr.foreach(print)
}
case Array(x,y) => {
arr.foreach(print)
}
}
三个case都能匹配到这个array但是只会执行第一个代码块。
case Array("zhangsan",_*) 能匹配以zhangsan开头,任意长度的数组
case Array(x,y) 能匹配任意两个长度的数组
4.List匹配
var list = "a"::"b"::"c"::Nil
list match{
case List("a","b","c") =>{
list.foreach(print)
}
case "a"::tail =>{
list.foreach(print)
}
}
这里两个同样也能匹配到list
case "a"::tail 可以匹配到以a开头任意长度的的list集合
5.类型匹配
var obj:String
obj match{
case x:Int=>{
print("Int")
}
case x:Double=>{
print("Double")
}
case x:String=>{
print("String")
}
}
6.Option匹配
简单说一下Option,Option可以看做一个装有值的容器
Some是Option的子类。Some()可以创建一个Option的子对象
使用其中的get方法可以取到值,若没有值,就会返回None对象(None是Option的子类)
var map :Map[String,String] = Map("a" -> "b")
map.get("a") match {
case Some("a") => print("a")
case Some("b") => print("b")
}
7.case class匹配
case class我之前说过了,这里是他的用法
def main(args: Array[String]): Unit = {
what(HonFuShi("255"))//other
what(HonFuShi("223"))//HonFuShi
what(new Apple("255"))//other
}
def what(apple: Apple) = {
apple match {
case BeautfulApple("223") => println("BeautfulApple")
case HonFuShi("223") => println("HonFuShi")
case _ => println("other")
}
}
class Apple(var weight:String)
case class HonFuShi(weight1:String) extends Apple(weight1)
case class BeautfulApple(weight1:String) extends Apple(weight1)
二、异常
先说一下执行顺序,执行try的代码若有异常,则终止try代码去执行catch里的代码,没有则不执行catch,无论是否有报错,最终都要执行finally的代码。
scala抛出异常和java唯一的区别在于,不需要在方法上写throws
def main(args: Array[String]): Unit = {
throw new RuntimeException("抛出异常")
}
然后说说异常的处理,我们和java对比来看吧
java
try{
throw new RuntimeException("异常")
}catch(IOException e){
}catch(RuntimeException e){
}finally{
//最终的操作,必须执行
}
scala
try{
throw new RuntimeException("异常")
}catch{
case e:RuntimeException => print(e.getMessage)
}finally{
//最终的操作,必须执行
}
不同之处 :
1.scala可以没有catch(不会捕获异常),都是java必须有catch
2.scala的异常捕获是和match模式匹配一样的,但是java是多个catch块
三、字符串
字符串的普通操作和java基本没区别,转正则就是调用r方法,没什么好说的
1.多行字符串
多行字符串在scala中的表达方式是
var rows = """
Hi I am
a String
"""
为了解决其中多余的空格问题,scala采用了
var str =
"""
|Hi I
|am
|Strng
|""".stripMargin
每一个|会被stripMargin解析成一行,stripMaegin有一个参数,可以改变这个解析字符,一般不用
2.字符串穿插属性
在scala中字符串的拼接不一定要用+ ,你可以在字符串前加s,就可以使用$属性的方式来拼接字符串
var str1 = "Hello"
var str2 = "Student"
var str3 = s"$str1 , I am a ${str2}"
$str必须保证其后面是空格,另一种写法随意
四、函数的一些高级用法
1.颗粒化函数
先来一个普通的有两个参数的函数,和它的调用
def sum(x:Int,y:Int):Int = {
x + y
}
sum(12,13)//25
然后是颗粒化函数
def sum(x:Int)(y:Int):Int = {
x + y
}
sum(12)(22)
那么问题来了,颗粒化函数有什么用呢,比如这样
def sum(x:Int)(y:Int):Int = {
x + y
}
var function0 : Int => Int = sum(1)
function0(1)
function0(2)
固定一个参数,使用时就只要传一个参数
2.高阶函数
这个在List集合用的会比较多,我先展示一下高阶函数的用法
var list = List(1,3,32,3,2,32,3,332)
var list2 = list.map(x => x + 1)
list2.foreach(println)//这里也是回调的一种高级写法,就像java里的foreach(out::print)
/*
2
4
33
4
3
33
4
333
*/
如果你学过java的lamda表达式,相信你很快就能领悟这种函数的用法
这里面x => x + 1就是你提供给底层的一个回调函数, 就是返回x + 1的一个函数,作用是让所有元素都加一
假如你函数只有一行且就是返回值,你可以这样去写
var list = List(1,3,32,3,2,32,3,332)
var list2 = list.filter(_ > 5)
println(list2.toString())
//List(32, 32, 332)
假如有两个参数都只使用一次,你也可以这样写
var list = List(1,3,32,3,2,32,3,332)
var sum = list.reduce(_ + _)
println(sum)//408
//等价于
var sum1 = list.reduce((x:Int ,y:Int) => x + y)
println(sum1)//408
reduce在java8里也有,如果大家感兴趣自己去搜,主要是讲两个参数的高阶函数的写法
五、隐式转换
1.隐式函数
implicit def abc(abc: Abc)={
new String("dff")
}
private val abc1 = new Abc()
println(abc1.concat("231"))
class Abc {}
看到这里你是不是有疑惑,为什么Abc类的对象可以使用String类的方法,这就是隐式函数,可以将所有属于该函数的参数类型的对象 识别出来,自动为其添加返回值类型对象的所有方法和属性。
就相当于把方法的参数那个类,添加了返回值那个类的所有方法。动态代理知道吧,就是那个道理
2.隐式参数
def function1(implicit x:Int){
print(x)
}
implicit var x = 21
function1//输出21
就是声明了隐式参数,就可以在调用前声明一个隐式变量,这样方法的入参就默认是这个变量
注意假如这里再声明一个implicit修饰的变量,调用会报错,如
def function1(implicit x:Int){
print(x)
}
implicit var x = 21
implicit var y = 21
function1//报错
3.隐式类型
implicit class ImplicitClass(x: Int){
def add() = {
x + 1
}
}
print(1.add)//2
和隐式方法差不多,就是给类构造器的参数类型的所有对象,添加这个类的方法和属性
好了,今天就暂时记录这么多!!!如果喜欢我的文章欢迎关注,我会继续更新我学算法的遇到的技术点。