一个综合小例子, 要严格区分 函数与方法 , 与 java 不一样
/**
* Scala 的值类型有 7 种
* Byte
* Char
* Short
* Int
* Long
* Float
* Double
*/
import scala.collection.mutable.ArrayBuffer
object Demo {
def main(args: Array[String]):Unit = {
val res = add(f);
val sex = "男"
val gender = if("男".equals(sex)) 1 else 0
println(gender)
println(res)
f2(5)
f3(2,3)
println(arr1.toBuffer)
arr2 += 1;
// 追加元组
arr2 += (2,3,4)
// 追加定常数组
arr2 ++= Array(5,6,7)
// 追加变长数组
arr2 ++= ArrayBuffer(8,9,10)
// 在指定位置插入 n 个 元素, n>=1 *args
arr2.insert(0,-3,-2,-1)
// 在指定位置 2 开始移除两个元素
arr2.remove(2,2)
for(i <- 0 until arr2.length ){
println(arr2(i))
}
println("*"*100)
arr2.foreach(println)
println("*"*100)
val v_i = for(i <- (0 to arr2.length).reverse) yield i*10
println(v_i.sum)
map_1.getOrElse("python", -1)
}
def add(f:(Int ,Int)=>Int):Int = {
f(3,4)
}
val f = (x:Int, y:Int) => x+y
val f2 = (n:Int) =>{
for (i <- 1 to n){
println(i)
}
}
val f3 = (n:Int, m:Int) =>{
for(i <- 1 to n; j <- 1 until m if i != j){
println(i*10+j)
}
}
val arr1 : Array[Int] = new Array[Int](8)
val arr3 = Array("java","scala","python")
val arr2 = ArrayBuffer[Int]()
val map_1 = Map("java"->1,"scala"->2,"python"->3)
val arr4 = Array(1,2,3)
arr3.zip(arr4)
}
// 延迟变量
object SharkTest{
def init():Unit={
println("call init()")
}
def main(args: Array[String]) {
lazy val res = init()
for(arg <-args){
println(arg)
}
println("in main...")
println(res)
}
}
object SharkTest{
def main(args: Array[String]) {
val list1 = List(3,2,1,4,5,8,7,9,6)
val list2 = list1.map(_ * 2)
val list_3 = list1.filter(_ % 2 == 0)
val list_4 = list1.sorted
val list5 = list_4.reverse
val list_6 = list1.grouped(4)
// 将 Iterator转换为 List
val list_7 = list_6.toList
val list_8 = List(List(1,2,3), List(4,5,6), List(7,8,9))
// 将多个 list 压扁
val list_9 = list_8.flatten
// 先 按照 空格 分割拆分后 再压平
val list_10 = List("java scala python array")
val list_11 = list_10.flatMap(_.split("\s+"))
val list_12 = list_10.map(_.split("\s+")).flatten
// 并行计算求和
val arr = Array(1,2,3,4,5,6,7,8,9,10)
// parallel
val res = arr.par.sum
val res2 = arr.par.reduce((x,y) => x+y)
// 有初始值,无特定顺序 则 每次 值不一定 125 135 65
val res3 = arr.par.fold(10)(_+_)
// 折叠 , 有初始值 (有特定值) 则 每次值 固定 65
val res4 = arr.par.foldLeft(10)(_+_)
// 聚合
val list_13 = List(List(1,2,3), List(3,4,5), List(2), List(0))
val res5 = list_13.flatMap(x=>x).reduce(_+_)
// base = 0
val res6 = list_13.aggregate(0)((base,y)=>base+y.sum,(x,y)=>x+y)
println(res6)
// 求并集
val l1 = List(5,6,4,7)
val l2 = List(1,2,3,4)
val res7 = l1 union l2
// 求交集
val res8 = l1 intersect l2
// 求差集
val res9 = l1 diff l2
}
}
### word count 小例子
object SharkTest{
def main(args: Array[String]) {
val lines = List("hello java hello python", "hello scala", "hello scala hello java hello scala")
val words = lines.flatMap(_.split("\s+"))
val words_pair = words.map(x=>(x,1))
println(words_pair)
val mp = words_pair.groupBy(_._1)
val res = mp.mapValues(l=>l.length)
val res2 = res.toList.sortBy{case(k,v)=>v}
/*
* Map(scala -> 3, java -> 2, hello -> 6, python -> 1)
* */
//mp.reduce((key,value)=>value.length)
// val it = words.groupBy(e=>e)
println(res2.reverse)
}
}
进入面向对象
/* 一个 源代码文件可以有多个 类与 多个 伴生对象 ,源文件的 名字也不用 与 class 保持一致,pulic 类修饰符 也不用,默认 public*/
class Person {
// 用 val 修饰的变量是只读的,相当于只有 get 方法, 没有 set 方法
val name : String = _
// 用 var 修饰的变量相当于既有 get 方法, 又有 set 方法
var race: String = _
// 用 private 修饰的 变量 属于私有变量 ,仅可在 本类与 伴生对象中 访问
private val id : Int = _
// private 并添加 [this] 限定后 ,这个 变量 就只能在 本类访问, 连伴生对象 都无法访问
private[this] val gender = _
}
object Person{
def main(args: Array[String]): Unit ={
val person = new Person()
}
}
模式匹配
object Demo{
def main(args:Array[String]):Unit={
val arr = Array("zhoudongyu","zhengshuang","guanxiaotong","yangzi")
matchCase(arr)
}
def matchCase(arr:Array[String]):Unit={
val name = arr(2)
println("name: "+name)
name match{
case "zhoudongyu" => println("周冬雨")
case "zhengshuang" => println("郑爽")
case "guanxiaotong" => println("关晓彤")
case "yangzi" => println("杨紫")
case _ => println("unknown")
}
}
}
private val func : PartialFunction[Int,String]= {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "others"
}
private val func2: Int=>String = x => x match{
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "others"
}
柯里化
scala 自带的 隐式转换
在交互式窗口
:implicit -v
// 自定义 隐式转换
package day04
class RichFile(file:String) {
def read():String={
Source.fromFile(file).mkString
}
object MyFile {
implicit def richFile(file:String) = new RichFile(file)
}
import day04.MyFile
val file:String=""
val content:String = MyFile.richFile(file).read()
这个隐式 好难理解
object ImplicitContext{
implicit object OrderingGirl extends Ordering[Girl]{
override def compare(x: Girl, y: Girl): Int = if(x.faceValue > y.faceValue) 1 else -1
}
}
class Girl(val name:String, var faceValue:Int){}
class Goddess[T: Ordering](val g1:T, val g2:T){
def choose()(implicit ord: Ordering[T]) = if (ord.gt(g1,g2)) g1 else g2
}
object Goddess {
def main(args:Array[String]):Unit={
import ImplicitContext.OrderingGirl
val g1 = new Girl("大佬",90)
val g2 = new Girl("小佬",80)
val goddess = new Goddess(g1,g2)
print(goddess.choose().name+"--"+goddess.choose().faceValue)
}
}
附 学习资源
水滴产品团队
面向 Scala 的技术博客
https://scala.cool/
https://scala.cool/tags/从-Java-到-Scala/
https://scala.cool/tags/Scala-类型的类型/
Scala 课堂!
http://twitter.github.io/scala_school/zh_cn/
优秀个人博客
http://hongjiang.info/scala/
Effective Scala
http://twitter.github.io/effectivescala/index-cn.html
官网
https://docs.scala-lang.org/
api
https://docs.scala-lang.org/api/all.html