scala Basic 第三课

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("""error""")
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)
  }
}

给已有的string类添加自己想要的方法,其实最早接触这种想法是在做c#开发时,c#已经引入了这种实现,不过是使用静态类的思路,这里scala也基本类似,不过是使用

它自己的implicit的语法。示例如下(来自scala cookbook)

implicit class StringImprovements(s: String) {
def increment = s.map(c => (c + 1).toChar)
 }

即普通的类定义前面加上一个implicit,然后是类名字里面使用是就是要扩展方法的基础类的参数。

原文地址:https://www.cnblogs.com/huaxiaoyao/p/5245844.html