Scala重点语法整理
①定义函数
def functionName ([list of parameters]):[return type]={
function body{
}
return[expr]
}
示例
def fun1(a:String,b:Int):Unit={
println("nima")
}
②函数传入方法
def time()={
println("Getting time in nano seconds")
System.nanoTime
}
def delayed( t:=>Long)={
println("In delayed method")
println("Param: "+ t)
}
def main(args:Array[String]):Unit={
delayed(time()) //先执行delayed方法体,执行到t时才执行内部传入的time()方法
}
}
/*
In delayed method
Getting time in nano seconds
Param: 1117398067174855
*/
③递归函数,for循环中反复调用自身
④String* 是该字符串可变长度的
⑤函数的参数是默认的情况
def addInt( a:Int=5, b:Int=7):Int={
var sum:Int=0
sum = a + b
return sum //执行时,缺省参数时,按照默认参数计算!!
}
⑥柯里函数:
柯里转换函数接受多个参数成一条链的函数,每次取一个参数。柯里函数是具有多个参数列表定义
def main(args:Array[String]){
val str1:String="Hello, "
val str2:String="Scala!"
println("str1 + str2 = "+ strcat(str1)(str2))
}
def strcat(s1:String)(s2:String)={
s1 + s2
}
⑦元组的使用
def main(args:Array[String]){
val t =(4,3,2,1)
val sum =t._1 + t._2 + t._3 + t._4
println("Sum of elements: "+ sum )
}
单机用Scala的actor来写word count
package cn.itcast.actor
import scala.actors.{Actor,Future}
import scala.collection.mutable.{HashSet,ListBuffer}
import scala.io.Source
/**
* Created by root on 2016/5/11.
*/
classTaskextendsActor{
override def act():Unit={
loop {
react {
caseSubmitTask(filename)=>{
//局部统计, 结果是Map[String, Int]
val result =Source.fromFile(filename).getLines().flatMap(_.split(" ")).map((_,1)).toList.groupBy(_._1).mapValues(_.size)
sender !ResultTask(result)//发送ResultTask, 用它来包装result
}
caseStopTask=>{
exit()
}
}
}
}
}
caseclassSubmitTask(filename:String)
caseclassResultTask(result :Map[String,Int])
case object StopTask
object ActorWordCount{
def main(args:Array[String]){
val replySet =newHashSet[Future[Any]]()
val resultList =newListBuffer[ResultTask]()//存储actor读取的内容
val files =Array[String]("c://words.txt","c://a.txt")
for(f <- files){
val actor =newTask
val reply = actor.start()!!SubmitTask(f)//启动, 并发送消息,返回Future
!
发送异步消息,没有返回值。
!?
发送同步消息,等待返回值。
!!
发送异步消息,返回值是 Future[Any]。
replySet += reply //把这些Future放到集合中
}
while(replySet.size >0){
val toCompute = replySet.filter(_.isSet)//取出有效的结果, 待处理的数据
for(f <- toCompute){
val result = f().asInstanceOf[ResultTask]//获取实例, 注意f后要加(), 调用apply(), 否则会报转换异常
resultList += result
replySet -= f
}
Thread.sleep(100)
}
//汇总的功能
//List((hello, 5), (tom,3), (helllo, 2), (jerry, 2))
val fr = resultList.flatMap(_.result).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2))
println(fr)
}
}