O'REILLY版《Programming Scala》学习笔记——基础语法部分
Scala 学习笔记
//方法定义格式:def methodName(param1:String,param2:Stirng):String={...}
val i=123 //整数类型赋值默认为Intval l=123L; val ll=123l //如果要赋Long值,需要在添加l或者L,这个和java的规则类似val b:Byte=127 //变量定义声明类型后可以用合适大小的整数为其赋值3.14e-5d //Double3.14e-5D //Double3.14e-5 //Double,默认3.14e-5f //Float,要指定为单精度浮点型需要加上f或者F,这个和java的规则类似3.14e-5F //Float
//示例代码 startdef tupleator(x1: Any, x2: Any, x3: Any) = (x1, x2, x3)val t = tupleator("Hello", 1, 2.3)println( "Print the whole tuple: " + t )println( "Print the first item: " + t._1 ) //用t._N得到第N个元素,这里索引从1开始而不是0(索引从1开始是函数式编程的惯例)println( "Print the second item: " + t._2 )println( "Print the third item: " + t._3 )val (t1, t2, t3) = tupleator("World", '!', 0x22)println( t1 + " " + t2 + " " + t3 )//示例代码 end//输出结果:Print the whole tuple: (Hello,1,2.3)Print the first item: HelloPrint the second item: 1Print the third item: 2.3World ! 34
stateCapitals.get("Unknown").getOrElse("Oops2!") //getOrElse 用法
scala> val list = List('b', 'c', 'd')list: List[Char] = List(b, c, d)scala> 'a' :: listres4: List[Char] = List(a, b, c, d)
val configFile = new java.io.File("~/.myapprc")val configFilePath = if (configFile.exists()) {configFile.getAbsolutePath()} else {configFile.createNewFile()configFile.getAbsolutePath()}
val dogBreeds = List("Doberman", "Yorkshire Terrier", "Dachshund","Scottish Terrier", "Great Dane", "Portuguese Water Dog")for (breed <- dogBreeds)println(breed)
for (breed <- dogBreedsif breed.contains("Terrier")) println(breed)
for (breed <- dogBreedsif breed.contains("Terrier");//多个过滤语句用";"分隔if !breed.startsWith("Yorkshire")) println(breed)
//符合过滤条件的元素添加到filteredBreeds 这个list里val filteredBreeds = for {breed <- dogBreedsif breed.contains("Terrier")//for语句使用"{}"包围的时候,多个过滤语句不用";"分隔if !breed.startsWith("Yorkshire")} yield breed
for {breed <- dogBreedsupcasedBreed = breed.toUpperCase()//upcasedBreed 在for语句里定义的变量(注意:没有使用val)} println(upcasedBreed)//upcasedBreed这里可以使用前面定义的变量
val sundries = List(23, "Hello", 8.5, 'q')for (sundry <- sundries) {sundry match {case i: Int => println("got an Integer: " + i)case s: String => println("got a String: " + s)case f: Double => println("got a Double: " + f)case other => println("got something else: " + other)//other 是匹配其他类型的通配符}}
val tupA = ("Good", "Morning!")val tupB = ("Guten", "Tag!")for (tup <- List(tupA, tupB)) {tup match { case (thingOne, thingTwo) if thingOne == "Good" => println("A two-tuple starting with 'Good'.")//if做更细粒度的匹配 case (thingOne, thingTwo) => println("This has two things: " + thingOne + " and " + thingTwo)}}
//强大的模式匹配,可以直接匹配对象属性case class Person(name: String, age: Int)val alice = new Person("Alice", 25)val bob = new Person("Bob", 32)val charlie = new Person("Charlie", 32)for (person <- List(alice, bob, charlie)) {person match {case Person("Alice", 25) => println("Hi Alice!")case Person("Bob", 32) => println("Hi Bob!")case Person(name, age) =>println("Who are you, " + age + " year-old person named " + name + "?")}}
val BookExtractorRE = """Book: title=([^,]+),\s+authors=(.+)""".r//调用String的r方法将字符串转成正则表达式val MagazineExtractorRE = """Magazine: title=([^,]+),\s+issue=(.+)""".rval catalog = List("Book: title=Programming Scala, authors=Dean Wampler, Alex Payne","Magazine: title=The New Yorker, issue=January 2009","Book: title=War and Peace, authors=Leo Tolstoy","Magazine: title=The Atlantic, issue=February 2009","BadData: text=Who put this here??")for (item <- catalog) { item match { case BookExtractorRE(title, authors) => println("Book "" + title + "", written by " + authors) case MagazineExtractorRE(title, issue) => println("Magazine "" + title + "", issue " + issue) case entry => println("Unrecognized entry: " + entry) }}