scala 基础笔记
view bound:必须传入一个隐式转换函数
class [T <% Ordered [T]]
content bound:必须传入一个隐式值
class [T : Ordering]
!异步发送消息
!? 同步发送消息,等待反馈信息
!!异步发送完成之后,返回一个future引用
scala列表操作符::把心元素整合到现有列表的最前端
scala里面Map 有2个特质:scala.collection.mutable 可变Map
scala.collection.immutable 不可变Map
scala 中如果一行开头用""" 表示开始 , 结尾用""" 表示结束
操作符和操作方法:
1+2 与(1).+(2) 表达的效果是一样
val s = "Hellon Word".toLowerCase 输出结果:hello word
for {句子} yield {循环体}
暂位符语法: _ > 0 坚持值是否大于 0
val f = (_: Int) +(_ : Int)
val b = sum(1, _: Int, 3) b(2) 输出结果 6
闭包减少代码
private def fileHere = new File(".").listFiles() def fileEnding(query: String) = { for (file <- fileHere; if file.getName.endsWith(query)) yield file } def fileContaining(query: String){ for (file <- fileHere; if file.getName.concat(query)) yield file } def filesRegex(query: String): Unit = { for (file <- fileHere; if file.getName.matches(query)) yield file } def fileMatching(query: String, matcher: (String, String) => Boolean){ for (file <- fileHere; if matcher(file.getName, query)) yield file }
优化后的结果:
一个方法之只要没有实现(即没有等号或者方法体) 它就是抽象的
具体(concrete)
多态动态绑定:
样本类和模式匹配:case class name 方便调用
abstract class CaseClass { case class Var(name: String) extends CaseClass case class Number(num: Double) extends CaseClass case class UnOp(operator: String, args: CaseClass) extends CaseClass case class BinOp(operator: String, left: CaseClass, right: CaseClass) extends CaseClass def caseTest(){ val v = Val("x") } def simplifyTop(cass: CaseClass) :CaseClass = cass match{ case UnOp("-",UnOp("-",e)) => e case BinOp("+", e, Number(0)) => e case BinOp("*", e, Number(0)) => e case _ => cass // 选择器 match {备选项} //的一个参数匹配“-”,第二个参数匹配e的值 //通配匹配 expr match{ case BinOp(op, left, right) => println(expr + "is a binarry operation") case _ => } expr match { case BinOp(_,_,_) => println(expr + "is a birarry operation") case _ => println("is something else ") } }
匹配固定长度序列模式
匹配任意长度序列模式
带有元组模式的匹配
类型模式匹配:
修改前:
class Person(var firstName: String, var secondName: String, var age: Int){ def getFirstName = firstName def getSecondName = secondName def GetAge = age def setFirstName(value:String):Unit = firstName = value def setLastName(value:String) = secondName = value def setAge(value:Int) = age = value override def toString = "[Person firstName:" + firstName + " lastName:" + secondName + " age:" + age + " ]" }
添加BeanProperty 后
如果在代码中加入 @scala.reflect.BeanProperty 就是相当于设置了get/set 方法
class Person(fn:String, ln:String, a:Int) { @scala.reflect.BeanProperty var firstName = fn @scala.reflect.BeanProperty var lastName = ln @scala.reflect.BeanProperty var age = a override def toString = "[Person firstName:" + firstName + " lastName:" + lastName + " age:" + age + " ]" }
读取文件信息
def findFileName(): Unit ={ val fileName = (new java.io.File(".")).listFiles() for { files <- fileName if files.listFiles() if files.getName.endsWith("scala") }System.out.print("file"+ files) }
列表:参见List列表http://www.cnblogs.com/zhanggl/p/4984512.html