二、Scala基础
1、变量:三种修饰符 -> ①val 常亮②var 变量③lazy val 惰性变量求值
2、类型
3、代码块 Block
{exp1;exp2}
或
{
exp1
exp2
}
4、函数
def functionName(param : paramType) : ReturnType = {
//function body : expressions
}
5、if表达式
if() val A else val B
6、for comprehension
用于循环的推导式
for {
x -> xs
y = x + 1
if (y > 0)
} yield y
7、match表达式
exp match {
case p1 => val 1
case p2 => val 2
……
case_ => val n
}
练习:
1、取得下面字符串中的汉字。
1477489369 0:0:0:0:0:0:0:1 cd60e43df3df2b490c517fff502f0684 3 1da6058be377160b14230637662921d7 (0,0,0,5,0,0,0,0) (SEARCH://search-fenzhi&desc-毛衣-male/?productList%5B1%5D%3D100129971676) NOCHANNEL QD_yyb R_84f63572b236e9e49f2e2e5cf885eb94 tag_sea
1 object ScalaTest1 { 2 3 def getChineseChar(str: String): Unit = { 4 val regex = "[\u4e00-\u9fa5]".r 5 var l = regex findAllIn str toList 6 7 for { 8 s <- l 9 } yield (print(s)) 10 } 11 12 def main(args: Array[String]): Unit = { 13 val str1: String = "1477489369" 14 val str2: String = "0:0:0:0:0:0:0:1" 15 val str3: String = "cd60e43df3df2b490c517fff502f0684" 16 val str4: String = "3" 17 val str5: String = "1da6058be377160b14230637662921d7" 18 val str6: String = "(0,0,0,5,0,0,0,0)" 19 val str7: String = "(SEARCH://search-fenzhi&desc-毛衣-male/?productList%5B1%5D%3D100129971676)" 20 val str8: String = "NOCHANNEL" 21 val str9: String = "QD_yyb" 22 val str10: String = "R_84f63572b236e9e49f2e2e5cf885eb94" 23 val str11: String = "tag_sea" 24 25 val list = str1 :: str2 :: str3 :: str4 :: str5 :: str6 :: str7 :: str8 :: str9 :: str10 :: str11 :: Nil 26 27 for { 28 s <- list 29 } getChineseChar(s) 30 } 31 }
2、将下面的单词和数字按列对齐并打印到控制台。
毛衣 1
毛衣毛衣 2
毛衣毛衣毛衣 3
毛衣毛衣毛衣毛衣 4
毛衣毛衣毛衣毛衣毛衣 5
毛衣毛衣毛衣毛衣毛衣毛衣 6
毛衣毛衣毛衣毛衣毛衣毛衣毛衣 7
毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣 8
毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣 9
毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣毛衣 10
1 object ScalaTest2 { 2 def forScala(n: Int): Unit = 3 for (i <- 1 to n) { 4 var str = new StringBuilder() 5 for (j <- 1 to i) { 6 str.append("毛衣") 7 } 8 str.append('\t') 9 str.append(i) 10 str.append('\n') 11 12 print(str) 13 } 14 15 def main(args: Array[String]): Unit = { 16 forScala(10) 17 } 18 }