首页 > 其他 > 详细

scala Basic 第三课

时间:2016-03-05 21:41:58      阅读:91      评论:0      收藏:0      [点我收藏+]

yield

在学习c#的时候学习过这个关键字,和这时的语义是一致的。
当你生成一个新的迭代器,而并不是想立刻使用,而是在其他地方使用的时候,可以延迟生成这个集合,
这时候yield关键字可以帮你完成这样的功能。
这就你是一个支票,可以让你在需要的时候向jvm取到集合数据。它是延迟实现的集合。
val a=for (i <- 1 to 10 if(i%7 ==0))
yield i
println(a)
a.foreach(println)

String的替换与查找:
val str="errors,"
str.replaceAll("[^a-zA-Z]","")
val log="there are some disk error, please check how to handler these error please!"
import scala.util.matching._
val r = new Regex("""\berror\b""")
r.findAllIn(log)
println(r)
单例对象可以和类具有相同的名称,此时该对象也被称为“伴生对象”。我们通常将伴生对象作为工厂使用。

val times = 1

times match {
  case 1 => "one"
  case 2 => "two"
  case _ => "some other number"
}
在最后一行指令中的_是一个通配符;它保证了我们可以处理所有的情况。
否则当传进一个不能被匹配的数字的时候,你将获得一个运行时错误。

case class
使用样本类可以方便得存储和匹配类的内容。你不用new关键字就可以创建它们。

case class ApacheAccessLog(ipAddress: String, clientIdentd: String,
                           userId: String, dateTime: String, method: String,
                           endpoint: String, protocol: String,
                           responseCode: Int, contentSize: Long) { 

} 

object ApacheAccessLog {
  val PATTERN = """^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) (\S+)" (\d{3}) (\d+)""".r 

  def parseLogLine(log: String): ApacheAccessLog = {
    val res = PATTERN.findFirstMatchIn(log)
    if (res.isEmpty) {
      throw new RuntimeException("Cannot parse log line: " + log)
    }
    val m = res.get
    ApacheAccessLog(m.group(1), m.group(2), m.group(3), m.group(4),
      m.group(5), m.group(6), m.group(7), m.group(8).toInt, m.group(9).toLong)
  }
}

scala Basic 第三课

原文:http://www.cnblogs.com/huaxiaoyao/p/5245844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!