yield
在學習c#的時候學習過這個關鍵字,和這時的語義是一致的。
當你生成一個新的迭代器,而并不是想立刻使用,而是在其他地方使用的時候,可以延遲生成這個集合,
這時候yield關鍵字可以幫你完成這樣的功能。
這就你是一個支票,可以讓你在需要的時候向jvm取到集合數據。它是延遲實現的集合。
val a=for (i <- 1 to 10 if(i%7 ==0))
yield i
println(a)
a.foreach(println)
scala菜鳥教程?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"
}
在最后一行指令中的_是一個通配符;它保證了我們可以處理所有的情況。
否則當傳進一個不能被匹配的數字的時候,你將獲得一個運行時錯誤。
scala helloworld,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.getApacheAccessLog(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)}
scala基礎語法?即普通的類定義前面加上一個implicit,然后是類名字里面使用是就是要擴展方法的基礎類的參數。