Scala

类型

object Hello extends App {  println("hello world")  println(1 + 1)  println(5 + 3*4)  println((5). + (3).*(4))  println("abc".size)  println("abc" + 4)}

表达式与条件

object ExpressionAndCondition extends App {  println(1 <= 2)  val a = 5 // 声明不变量  val b = 6  if (a < b) {    println("true")  }else {    println("false")  }}
var i = 1while (i <= 3){  println(i)  i += 1}
for(i <- args.indices){  println(args(i))}args.foreach(str => println(str)) // 函数式

范围

val r1 = 1 to 10 by 2 // 步长为2val r2 = 1 to 10 // 步长为1val r3 = 1 until 10 by 2 // 步长为2 不包括10

元组

val name = ("c", "xk")println(name._1 + name._2)val (x, y) = (1, 2)println(x+y)

class User(username: String, password: String) // pojo类class UserService {  val user = new User("cxk", "123")  def printUser(){    println(user)  }}new UserService().printUser

构造器

class User(username: String){  def this(username: String, password: String){    this(username)    println(password)  }}

扩展类

object singleton { // 单例对象  def print = println("he") // 类方法}singleton.print
class Father(val name: String){  def say = println("i am f")}class Son(override val name: String, val age: Int) extends Father(name){  override def say: Unit = {    super.say    println("i am s")  }}new Son("cx",1).say
trait Part {  def say = println("i am say")}class Person extends Object with Part{}new Person().say

函数定义

def add(a: Int, b: Int): Int = a+bprintln(add(1,2))

集合

val list = List(1,2,3)println(list(2))println(list == List(1,2,3))
val set = Set(1,2,3)println(set - 2) // 集合运算println(set + 5)println(set -- Set(1,2)) // 集合间运算println(set ++ Set(5,6))println(set == Set(1,2,3))
val map = Map("name" -> "cxk","age" -> 18) // 不可变mapprintln(map("name"))val mMap = new mutable.HashMap[String, Any] // 可变mapmMap += "name" -> "cxk"mMap += "age" -> 18

集合函数

val list = List(1,2,3)println(list.isEmpty)println(list.length)println(list.size)println(list.head)println(list.tail) // 返回去除第一个元素的listprintln(list.last)println(list.init) // 返回去除最后一个元素的listprintln(list.reverse) // 都不会修改原列表println(list.drop(1))println(list.count(i => i >= 2)) // 计算符合条件的元素个数println(list.filter(i => i >=2)) // 将符合条件的元素拿出来println(list.map(i => i *2))println(list.exists(i => i > 2)) // 是否存在这一的一个元素println(list.sortWith((a,b) => a > b))println((0 /: list){(sum, i) => sum+i}) // 从初始值0开始累加println(list.foldLeft(0)((sum,i) => sum + i))list.foreach(i => println(i))val map = Map("name" -> "cxk", "age" -> 18)map.foreach(entry => println(entry._1 + entry._2))

Any 和 Nothing

Any是所有类型的父类 Nothing是所有类型的子类 Null是一个Trait null是Null的实例

屏幕截图 2020-11-12 085642

模式匹配

def switch(i: String): String = i match {  case "1" => "one"  case "2" => "two"  case _ => "none"}println(switch("1"))println(switch("ss"))
val reg = """\w""".r // 创建一个正则println(reg.findFirstIn("i am your"))

并发

...

核心优势

不足