scala学习草稿

本篇博客纯属个人草稿,本着好读书不求甚解的态度,对于自己以往的学习进行简单的整理。博主会在文章开头写明大致脉络,欢迎指正错误,谢谢!

文章目录

1、安装scala与idea编辑器

2、scala基础

3、scala数据结构

4、scala面向对象

5、akka示例

1、安装scala与idea编辑器

操作简单,可自行百度

2、scala基础

2.1 声明变量

object VariableTest {
  def main(args: Array[String]) {
    //使用val定义的变量值是不可变的,相当于java里用final修饰的变量
    val i = 1
    //使用var定义的变量是可变得,在Scala中鼓励使用val
    var s = "hello"
    //Scala编译器会自动推断变量的类型,必要的时候可以指定类型
    //变量名在前,类型在后
    val str: String = "world"
  }
}

2.2 常用类型

scala和Java一样,有7种数值类型 Byte Char Short Int Float Double Boolean

2.3 条件表达式

object ConditionTest{
  def main(args: Array[String]) {
    val x = 1
    //判断x的值,将结果赋给y
    val y = if (x > 0) 1 else -1
    //打印y的值
    println(y)

    //支持混合类型表达式
    val z = if (x > 1) 1 else "error"
    //打印z的值
    println(z)

    //如果缺失else,相当于if (x > 2) 1 else ()
    val m = if (x > 2) 1
    println(m)

    //在scala中每个表达式都有值,scala中有个Unit类,写做(),相当于Java中的void
    val n = if (x > 2) 1 else ()
    println(n)

    //if和else if
    val k = if (x < 0) 0
    else if (x >= 1) 1 else -1
    println(k)
  }
}

2.4 块表达式

object BlockExpressionTest {
  def main(args: Array[String]) {
    val x = 0
    //在scala中{}中课包含一系列表达式,块中最后一个【表达式】的值就是块的值
    //下面就是一个块表达式
    val result = {
      if (x < 0) {
        -1
      } else if (x >= 1) {
        1
      } else {
        "error"
      }
    }
    //result的值就是块表达式的结果
    println(result)
  }
}

2.5 循环

object ForTest {
  def main(args: Array[String]) {
    //for(i <- 表达式),表达式1 to 10返回一个Range(区间)
    //每次循环将区间中的一个值赋给i
    for (i <- 1 to 10)
      println(i)

    //for(i <- 数组)
    val arr = Array("a", "b", "c")
    for (i <- arr)
      println(i)

    //高级for循环
    //每个生成器都可以带一个条件,注意:if前面没有分号
    for (i <- 1 to 3; j <- 1 to 3 if i != j)
      print((10 * i + j) + " ")
    println()

    //for推导式:如果for循环的循环体以yield开始,则该循环会构建出一个集合
    //每次迭代生成集合中的一个值
    val v = for (i <- 1 to 10) yield i * 10
    println(v) // Vector(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

  }

}

2.6 调用方法和函数

Scala中的+ - * / %等操作符的作用与Java一样,位操作符 & | ^>> <<也一样。只是有
一点特别的:这些操作符实际上是方法。例如:
a + b
是如下方法调用的简写:
a.+(b)

a 方法 b可以写成a.方法(b)

2.7 方法和函数

简记:方法有def 函数时火箭 =>

object MethodAndFunctionTest {
  //定义一个方法
  //方法m2参数要求是一个函数,函数的参数必须是两个Int类型
  //返回值类型也是Int类型
  def m1(f: (Int, Int) => Int): Int = {
    f(2, 6)
  }

  //不管是方法还是函数,都必须有数据类型

  //定义一个函数f1,参数是两个Int类型,返回值是一个Int类型
  val f1 = (x: Int, y: Int) => x + y
  //再定义一个函数f2
  val f2 = (m: Int, n: Int) => m * n

  //main方法
  def main(args: Array[String]) {

    //调用m1方法,并传入f1函数
    val r1 = m1(f1)
    println(r1)

    //调用m1方法,并传入f2函数
    val r2 = m1(f2)
    println(r2)
  }
}

2.8 方法与函数的互操作

scala> def m1(x:Int,y:Int):Int = x* y
m1: (x: Int, y: Int)Int

scala> val f1 = (x:Int,y:Int)=>x*y
f1: (Int, Int) => Int = $$Lambda$1050/280397810@55f4887d

scala> val f2 = m1 _ //仅需一个 _ 就能够将方法转为lambda函数
f2: (Int, Int) => Int = $$Lambda$1057/358849801@4fba8eec

3、scala数据结构

3.1 数组

3.1.1 定长数组和边长数组
import scala.collection.mutable.ArrayBuffer


object ArrayTest {
  def main(args: Array[String]) {
    //初始化一个长度为8的定长数组,其所有元素均为0
    val arr1 = new Array[Int](8)
    //直接打印定长数组,内容为数组的hashcode值
    println(arr1)
    //将数组转换成数组缓冲,就可以看到原数组中的内容了
    //toBuffer会将数组转换长数组缓冲
    println(arr1.toBuffer)

    //注意:如果new,相当于调用了数组的apply方法,直接为数组赋值
    //初始化一个长度为10的定长数组
    val arr2 = Array[Int](10)
    println(arr2.toBuffer)

    //定义一个长度为3的定长数组
    val arr3 = Array("hadoop", "storm", "spark")
    //使用()来访问元素
    println(arr3(2))

    //
    //变长数组(数组缓冲)
    //如果想使用数组缓冲,需要导入import scala.collection.mutable.ArrayBuffer包
    val ab = ArrayBuffer[Int]()
    //向数组缓冲的尾部追加一个元素
    //+=尾部追加元素
    ab += 1
    //追加多个元素
    ab += (2, 3, 4, 5)
    //追加一个数组++=
    ab ++= Array(6, 7)
    //追加一个数组缓冲
    ab ++= ArrayBuffer(8,9)
    //打印数组缓冲ab

    //在数组某个位置插入元素用insert
    ab.insert(0, -1, 0)
    //删除数组某个位置的元素用remove
    ab.remove(8, 2)
    println(ab)
  }
}
3.1.2 遍历数组
object ForArrayTest {

  def main(args: Array[String]) {
    //初始化一个数组
    val arr = Array(1,2,3,4,5,6,7,8)
    //增强for循环
    for(i <- arr)
      println(i)

    //好用的until会生成一个Range
    //reverse是将前面生成的Range反转
    for(i <- (0 until arr.length).reverse)
      println(arr(i))
  }
}
3.1.3 数组转换
object ArrayYieldTest {
  def main(args: Array[String]) {
    //定义一个数组
    val arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
    //将偶数取出乘以10后再生成一个新的数组
    val res = for (e <- arr if e % 2 == 0) yield e * 10
    println(res.toBuffer)

    //更高级的写法,用着更爽
    //filter是过滤,接收一个返回值为boolean的函数
    //map相当于将数组中的每一个元素取出来,应用传进去的函数
    val r = arr.filter(_ % 2 == 0).map(_ * 10)
    println(r.toBuffer)

  }
}
3.1.4 数组常用算法
scala> val arr = Array(2,5,1,4,3)
arr: Array[Int] = Array(2, 5, 1, 4, 3)

scala> arr.sum
res0: Int = 15

scala> arr.max
res1: Int = 5

scala> arr.sorted
res2: Array[Int] = Array(1, 2, 3, 4, 5)

3.2 映射(字典)

scala> val scores = Map("tom"-> 85,"jerry"->99,"kitty"->90)
scores: scala.collection.immutable.Map[String,Int] = Map(tom -> 85, jerry -> 99, kitty -> 90)

scala> val scores = Map(("tom",85),("jerry",99),("kitty",90))
scores: scala.collection.immutable.Map[String,Int] = Map(tom -> 85, jerry -> 99, kitty -> 90)
scala> scores("jerry") = 80
<console>:13: error: value update is not a member of scala.collection.immutable.Map[String,Int]
       scores("jerry") = 80
scala> scores += ("kim"->12)
<console>:13: error: value += is not a member of scala.collection.immutable.Map[String,Int]
  Expression does not convert to assignment because receiver is not assignable.
       scores += ("kim"->12)

scala> val scores = scala.collection.mutable.Map(("tom",85),("jerry",99),("kitty",90))
scores: scala.collection.mutable.Map[String,Int] = Map(tom -> 85, kitty -> 90, jerry -> 99)

scala> scores("jerry") = 80

scala> scores += ("kim"->12)
res9: scores.type = Map(tom -> 85, kitty -> 90, kim -> 12, jerry -> 80)

3.3 元组

scala> val t = (1,2.0,"tom")
t: (Int, Double, String) = (1,2.0,tom)

scala> t._1
res11: Int = 1

scala> t._3
res12: String = tom

scala> val arr = Array(("tom",85),("jerry",99))
arr: Array[(String, Int)] = Array((tom,85), (jerry,99))

scala> arr.toMap
res13: scala.collection.immutable.Map[String,Int] = Map(tom -> 85, jerry -> 99)

scala> val names = Array("tom","sam","kim")
names: Array[String] = Array(tom, sam, kim)

scala> val scores = Array(10,20,30)
scores: Array[Int] = Array(10, 20, 30)

scala> val ns = names.zip(scores)
ns: Array[(String, Int)] = Array((tom,10), (sam,20), (kim,30))

scala> ns.toMap
res14: scala.collection.immutable.Map[String,Int] = Map(tom -> 10, sam -> 20, kim -> 30)

3.4 集合

Scala的集合有三大类:序列Seq、集Set、映射Map,所有的集合都扩展自Iterable特质

在Scala中集合有可变(mutable)和不可变(immutable)两种类型,immutable类型的集合初始化后就不能改变了(注意与val修饰的变量进行区别)

3.4.1 序列

不可变的序列 import scala.collection.immutable._

在Scala中列表要么为空(Nil表示空列表)要么是一个head元素加上一个tail列表。

9 :: List(5, 2)  :: 操作符是将给定的头和尾创建一个新的列表

注意::: 操作符是右结合的,如9 :: 5 :: 2 :: Nil相当于 9 :: (5 :: (2 :: Nil)

object ImmutListTest {

  def main(args: Array[String]) {
    //创建一个不可变的集合
    val lst1 = List(1,2,3)
    //将0插入到lst1的前面生成一个新的List
    val lst2 = 0 :: lst1
    val lst3 = lst1.::(0)
    val lst4 = 0 +: lst1
    val lst5 = lst1.+:(0)

    //将一个元素添加到lst1的后面产生一个新的集合
    val lst6 = lst1 :+ 3

    val lst0 = List(4,5,6)
    //将2个list合并成一个新的List
    val lst7 = lst1 ++ lst0  (这个常用)
    //将lst0插入到lst1前面生成一个新的集合
    val lst8 = lst1 ++: lst0

    //将lst0插入到lst1前面生成一个新的集合
    val lst9 = lst1.:::(lst0)

    println(lst9)
  }
}
object MuListTest {
  def main(args: Array[String]): Unit = {
    //构建一个可变列表,初始有3个元素1,2,3
    val lst0 = ListBuffer[Int](1, 2, 3)
    //创建一个空的可变列表
    val lst1 = new ListBuffer[Int]
    //向lst1中追加元素,注意:没有生成新的集合
    lst1 += 4
    lst1.append(5)

    //将lst1中的元素最近到lst0中, 注意:没有生成新的集合
    lst0 ++= lst1

    //将lst0和lst1合并成一个新的ListBuffer 注意:生成了一个集合
    val lst2 = lst0 ++ lst1

    //将元素追加到lst0的后面生成一个新的集合
    val lst3 = lst0 :+ 5

  }
}

4、scala面向对象

4.1 lazy特性

scala> import scala.io.Source
import scala.io.Source
scala> val file = Source.fromFile("./test.csv")
java.io.FileNotFoundException: ./test.csv (No such file or directory)
  at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)
  ... 28 elided

scala> lazy val file = Source.fromFile("./test.csv")
file: scala.io.BufferedSource = <lazy>

scala> for (line <- file )
     | println(line)
java.io.FileNotFoundException: ./test.csv (No such file or directory)
  at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)
  at .file$lzycompute(<console>:12)
  at .file(<console>:12)
  ... 29 elided

scala> 

4.2 类与对象

4.3 继承

5.模式匹配和样例类

6.偏函数

object PartialFuncDemo {
/*被包在花括号内没有match的一组case语句是一个偏函数,它是PartialFunction[A, B]的一个实例,A代表参数类型,B代表返回类型,常用作输入模式匹配*/
  def func1: PartialFunction[String, Int] = {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def func2(num: String): Int = num match {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def main(args: Array[String]) {
    println(func1("one"))
    println(func2("one"))
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值