关闭

Scala简明教程(2)

标签: scala教程基础
459人阅读 评论(0) 收藏 举报
分类:

Scala简明教程(2)

包Package

import scala.collection._  //通配符导入,类似java中的.*
import scala.collection.Vector
import scala.collection.{Vector, Sequence}  //导入多个
import scala.collection.{Vector => Vec28}  //别名.
import java.util.{Date => _, _}  //除了Date,其它都导入
package pkg at start of file
package pkg { ... }

一般语句后面可以省略 ;


数据结构

tuple类型

(1,2,3)
var (x,y,z) = (1,2,3)

List类型

var xs = List(1,2,3)
xs(2)

一些特殊的操作符

1 :: List(2,3)
List(1, 2) ::: List(2, 3)
List(1, 2) ++ Set(3, 4, 3)

range

1 to 5 same as 1 until 6
1 to 10 by 2

字符串

s前缀, 替换字符串中的变量或表达式

val name = "James"
println(s"Hello, $name") // Hello, James
println(s"1 + 1 = ${1 + 1}")

f前缀, printf风格的格式化

val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall

raw前缀, 原始字符,不转义

scala> raw"a\nb"
res1: String = a\nb

r后缀, 正则表达式

scala> "a".r
res1: scala.util.matching.Regex = a

自定义的字符串拦截器

implicit class JsonHelper(private val sc: StringContext) extends AnyVal {
  def json(args: Any*): JSONObject = ...
}
val x: JSONObject = json"{ a: $a }"

控制流程
if语句

if (check) happy else sad
if (check) happy   //下面一样
if (check) happy else ()

while语句

import scala.util.control.Breaks._
breakable {
  for (x <- xs) {
    if (Math.random < 0.1) break
  }
}
for (x <- xs if x%2 == 0) yield x*10 //与下面的等价
xs.filter(_%2 == 0).map(_*10)
for ((x,y) <- xs zip ys) yield x*y //与下面的等价
(xs zip ys) map { case (x,y) => x*y }
for (x <- xs; y <- ys) yield x*y  //与下面的等价
xs flatMap {x => ys map {y => x*y}}
for (x <- xs; y <- ys) { //双层嵌套,类似for {for {}}
println("%d/%d = %.1f".format(x,y, x*y))
}
for (i <- 1 to 5) {
println(i)
}
for (i <- 1 until 5) {
println(i)
}

模式匹配
case class自动生成equals和toString,参数相同则==返回true

(xs zip ys) map { case (x,y) => x*y }
val v42 = 42
Some(3) match {
case Some(`v42`) => println("42")
case _ => println("Not 42")
}
val UppercaseVal = 42
Some(3) match {
case Some(UppercaseVal) => println("42")
case _ => println("Not 42")
}
1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:120913次
    • 积分:2730
    • 等级:
    • 排名:第13693名
    • 原创:144篇
    • 转载:9篇
    • 译文:0篇
    • 评论:15条
    博客专栏
    Spark

    文章:16篇

    阅读:29637
    最新评论