加载中...

Scala


其中 Y=Scala

源代码下载: learnscala-zh.scala

Scala - 一门可拓展的语言

  1. /*
  2. 自行设置:
  3. 1) 下载 Scala - http://www.scala-lang.org/downloads
  4. 2) unzip/untar 到您喜欢的地方,并把 bin 子目录添加到 path 环境变量
  5. 3) 在终端输入 scala,启动 Scala 的 REPL,您会看到提示符:
  6. scala>
  7. 这就是所谓的 REPL (读取-求值-输出循环,英语: Read-Eval-Print Loop),
  8. 您可以在其中输入合法的表达式,结果会被打印。
  9. 在教程中我们会进一步解释 Scala 文件是怎样的,但现在先了解一点基础。
  10. */
  11. /////////////////////////////////////////////////
  12. // 1\. 基础
  13. /////////////////////////////////////////////////
  14. // 单行注释开始于两个斜杠
  15. /*
  16. 多行注释,如您之前所见,看起来像这样
  17. */
  18. // 打印并强制换行
  19. println("Hello world!")
  20. println(10)
  21. // 没有强制换行的打印
  22. print("Hello world")
  23. // 通过 var 或者 val 来声明变量
  24. // val 声明是不可变的,var 声明是可修改的。不可变性是好事。
  25. val x = 10 // x 现在是 10
  26. x = 20 // 错误: 对 val 声明的变量重新赋值
  27. var y = 10
  28. y = 20 // y 现在是 20
  29. /*
  30. Scala 是静态语言,但注意上面的声明方式,我们没有指定类型。
  31. 这是因为类型推导的语言特性。大多数情况, Scala 编译器可以推测变量的类型,
  32. 所以您不需要每次都输入。可以像这样明确声明变量类型:
  33. */
  34. val z: Int = 10
  35. val a: Double = 1.0
  36. // 注意从 Int 到 Double 的自动转型,结果是 10.0, 不是 10
  37. val b: Double = 10
  38. // 布尔值
  39. true
  40. false
  41. // 布尔操作
  42. !true // false
  43. !false // true
  44. true == false // false
  45. 10 > 5 // true
  46. // 数学运算像平常一样
  47. 1 + 1 // 2
  48. 2 - 1 // 1
  49. 5 * 3 // 15
  50. 6 / 2 // 3
  51. 6 / 4 // 1
  52. 6.0 / 4 // 1.5
  53. // 在 REPL 计算一个表达式会返回给您结果的类型和值
  54. 1 + 7
  55. /* 上行的结果是:
  56. scala> 1 + 7
  57. res29: Int = 8
  58. 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8
  59. 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果,
  60. 您看到的输出可能不一样。
  61. */
  62. "Scala strings are surrounded by double quotes"
  63. 'a' // Scala 的字符
  64. // '不存在单引号字符串' <= 这会导致错误
  65. // String 有常见的 Java 字符串方法
  66. "hello world".length
  67. "hello world".substring(2, 6)
  68. "hello world".replace("C", "3")
  69. // 也有一些额外的 Scala 方法,另请参见:scala.collection.immutable.StringOps
  70. "hello world".take(5)
  71. "hello world".drop(5)
  72. // 字符串改写:留意前缀 "s"
  73. val n = 45
  74. s"We have $n apples" // => "We have 45 apples"
  75. // 在要改写的字符串中使用表达式也是可以的
  76. val a = Array(11, 9, 6)
  77. s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
  78. s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
  79. s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
  80. // 添加 "f" 前缀对要改写的字符串进行格式化
  81. f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
  82. f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
  83. // 未处理的字符串,忽略特殊字符。
  84. raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
  85. // 一些字符需要转义,比如字符串中的双引号
  86. "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
  87. // 三个双引号可以使字符串跨越多行,并包含引号
  88. val html = """<form id="daform">
  89. <p>Press belo', Joe</p>
  90. <input type="submit">
  91. </form>"""
  92. /////////////////////////////////////////////////
  93. // 2\. 函数
  94. /////////////////////////////////////////////////
  95. // 函数可以这样定义:
  96. //
  97. // def functionName(args...): ReturnType = { body... }
  98. //
  99. // 如果您以前学习过传统的编程语言,注意 return 关键字的省略。
  100. // 在 Scala 中, 函数代码块最后一条表达式就是返回值。
  101. def sumOfSquares(x: Int, y: Int): Int = {
  102. val x2 = x * x
  103. val y2 = y * y
  104. x2 + y2
  105. }
  106. // 如果函数体是单行表达式,{ } 可以省略:
  107. def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
  108. // 函数调用的语法是熟知的:
  109. sumOfSquares(3, 4) // => 25
  110. // 在多数情况下 (递归函数是需要注意的例外), 函数返回值可以省略,
  111. // 变量所用的类型推导一样会应用到函数返回值中:
  112. def sq(x: Int) = x * x // 编译器会推断得知返回值是 Int
  113. // 函数可以有默认参数
  114. def addWithDefault(x: Int, y: Int = 5) = x + y
  115. addWithDefault(1, 2) // => 3
  116. addWithDefault(1) // => 6
  117. // 匿名函数是这样的:
  118. (x:Int) => x * x
  119. // 和 def 不同,如果语义清晰,匿名函数的参数类型也可以省略。
  120. // 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。
  121. val sq: Int => Int = x => x * x
  122. // 匿名函数的调用也是类似的:
  123. sq(10) // => 100
  124. // 如果您的匿名函数中每个参数仅使用一次,
  125. // Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见,
  126. // 在数据结构部分会明显可见。
  127. val addOne: Int => Int = _ + 1
  128. val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3)
  129. addOne(5) // => 6
  130. weirdSum(2, 4) // => 16
  131. // return 关键字是存在的,但它只从最里面包裹了 return 的 def 函数中返回。
  132. // 警告: 在 Scala 中使用 return 容易出错,应该避免使用。
  133. // 在匿名函数中没有效果,例如:
  134. def foo(x: Int): Int = {
  135. val anonFunc: Int => Int = { z =>
  136. if (z > 5)
  137. return z // 这一行令 z 成为 foo 函数的返回值!
  138. else
  139. z + 2 // 这一行是 anonFunc 函数的返回值
  140. }
  141. anonFunc(x) // 这一行是 foo 函数的返回值
  142. }
  143. /*
  144. * 译者注:此处是指匿名函数中的 return z 成为最后执行的语句,
  145. * 在 anonFunc(x) 下面的表达式(假设存在)不再执行。如果 anonFunc
  146. * 是用 def 定义的函数, return z 仅返回到 anonFunc(x) ,
  147. * 在 anonFunc(x) 下面的表达式(假设存在)会继续执行。
  148. */
  149. /////////////////////////////////////////////////
  150. // 3\. 控制语句
  151. /////////////////////////////////////////////////
  152. 1 to 5
  153. val r = 1 to 5
  154. r.foreach( println )
  155. r foreach println
  156. // 附注: Scala 对点和括号的要求想当宽松,注意其规则是不同的。
  157. // 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。
  158. (5 to 1 by -1) foreach ( println )
  159. // while 循环
  160. var i = 0
  161. while (i < 10) { println("i " + i); i+=1 }
  162. while (i < 10) { println("i " + i); i+=1 } // 没错,再执行一次,发生了什么?为什么?
  163. i // 显示 i 的值。注意 while 是经典的循环方式,它连续执行并改变循环中的变量。
  164. // while 执行很快,比 Java 的循环快,但像上面所看到的那样用组合子和推导式
  165. // 更易于理解和并行化。
  166. // do while 循环
  167. do {
  168. println("x is still less than 10");
  169. x += 1
  170. } while (x < 10)
  171. // Scala 中尾递归是一种符合语言习惯的递归方式。
  172. // 递归函数需要清晰的返回类型,编译器不能推断得知。
  173. // 这是一个 Unit。
  174. def showNumbersInRange(a:Int, b:Int):Unit = {
  175. print(a)
  176. if (a < b)
  177. showNumbersInRange(a + 1, b)
  178. }
  179. showNumbersInRange(1,14)
  180. // 条件语句
  181. val x = 10
  182. if (x == 1) println("yeah")
  183. if (x == 10) println("yeah")
  184. if (x == 11) println("yeah")
  185. if (x == 11) println ("yeah") else println("nay")
  186. println(if (x == 10) "yeah" else "nope")
  187. val text = if (x == 10) "yeah" else "nope"
  188. /////////////////////////////////////////////////
  189. // 4\. 数据结构
  190. /////////////////////////////////////////////////
  191. val a = Array(1, 2, 3, 5, 8, 13)
  192. a(0)
  193. a(3)
  194. a(21) // 抛出异常
  195. val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
  196. m("fork")
  197. m("spoon")
  198. m("bottle") // 抛出异常
  199. val safeM = m.withDefaultValue("no lo se")
  200. safeM("bottle")
  201. val s = Set(1, 3, 7)
  202. s(0)
  203. s(1)
  204. /* 这里查看 map 的文档 -
  205. * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
  206. * 并确保你会阅读
  207. */
  208. // 元组
  209. (1, 2)
  210. (4, 3, 2)
  211. (1, 2, "three")
  212. (a, 2, "three")
  213. // 为什么有这个?
  214. val divideInts = (x:Int, y:Int) => (x / y, x % y)
  215. divideInts(10,3) // 函数 divideInts 同时返回结果和余数
  216. // 要读取元组的元素,使用 _._n,n是从1开始的元素索引
  217. val d = divideInts(10,3)
  218. d._1
  219. d._2
  220. /////////////////////////////////////////////////
  221. // 5\. 面向对象编程
  222. /////////////////////////////////////////////////
  223. /*
  224. 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。
  225. 这些表达式可以输入到命令行解释器中作为快速测试,但它们不能独立存在于 Scala
  226. 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。相反 Scala 文件
  227. 允许的顶级结构是:
  228. - objects
  229. - classes
  230. - case classes
  231. - traits
  232. 现在来解释这些是什么。
  233. */
  234. // 类和其他语言的类相似,构造器参数在类名后声明,初始化在类结构体中完成。
  235. class Dog(br: String) {
  236. // 构造器代码在此
  237. var breed: String = br
  238. // 定义名为 bark 的方法,返回字符串
  239. def bark = "Woof, woof!"
  240. // 值和方法作用域假定为 public。"protected" 和 "private" 关键字也是可用的。
  241. private def sleep(hours: Int) =
  242. println(s"I'm sleeping for $hours hours")
  243. // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类必须被声明为 abstract
  244. // abstract class Dog(...) { ... }
  245. // def chaseAfter(what: String): String
  246. }
  247. val mydog = new Dog("greyhound")
  248. println(mydog.breed) // => "greyhound"
  249. println(mydog.bark) // => "Woof, woof!"
  250. // "object" 关键字创造一种类型和该类型的单例。
  251. // Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例
  252. // 共用的行为则放入 object 中。两者的区别和其他语言中类方法和静态方法类似。
  253. // 请注意 object 和 class 可以同名。
  254. object Dog {
  255. def allKnownBreeds = List("pitbull", "shepherd", "retriever")
  256. def createDog(breed: String) = new Dog(breed)
  257. }
  258. // Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类
  259. // 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值
  260. // 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变
  261. // 数据。它们通常只有几个方法,且方法几乎没有副作用。
  262. case class Person(name: String, phoneNumber: String)
  263. // 创造新实例,注意 case 类不需要使用 "new" 关键字
  264. val george = Person("George", "1234")
  265. val kate = Person("Kate", "4567")
  266. // 使用 case 类,您可以轻松得到一些功能,像 getters:
  267. george.phoneNumber // => "1234"
  268. // 每个字段的相等性比较(无需覆盖 .equals)
  269. Person("George", "1234") == Person("Kate", "1236") // => false
  270. // 简单的拷贝方式
  271. // otherGeorge == Person("george", "9876")
  272. val otherGeorge = george.copy(phoneNumber = "9876")
  273. // 还有很多。case 类同时可以用于模式匹配,接下来会看到。
  274. // 敬请期待 Traits !
  275. /////////////////////////////////////////////////
  276. // 6\. 模式匹配
  277. /////////////////////////////////////////////////
  278. // 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。
  279. // 附注:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的
  280. // fall-through 现象不会发生。
  281. def matchPerson(person: Person): String = person match {
  282. // Then you specify the patterns:
  283. case Person("George", number) => "We found George! His number is " + number
  284. case Person("Kate", number) => "We found Kate! Her number is " + number
  285. case Person(name, number) => "We matched someone : " + name + ", phone : " + number
  286. }
  287. val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则
  288. // 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。
  289. // Scala 中您可以匹配很多东西:
  290. def matchEverything(obj: Any): String = obj match {
  291. // 匹配值:
  292. case "Hello world" => "Got the string Hello world"
  293. // 匹配类型:
  294. case x: Double => "Got a Double: " + x
  295. // 匹配时指定条件
  296. case x: Int if x > 10000 => "Got a pretty big number!"
  297. // 像之前一样匹配 case 类:
  298. case Person(name, number) => s"Got contact info for $name!"
  299. // 匹配正则表达式:
  300. case email(name, domain) => s"Got email address $name@$domain"
  301. // 匹配元组:
  302. case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c"
  303. // 匹配数据结构:
  304. case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c"
  305. // 模式可以嵌套
  306. case List(List((1, 2,"YAY"))) => "Got a list of list of tuple"
  307. }
  308. // 事实上,你可以对任何有 "unapply" 方法的对象进行模式匹配。
  309. // 这个特性如此强大以致于 Scala 允许定义一个函数作为模式匹配:
  310. val patternFunc: Person => String = {
  311. case Person("George", number) => s"George's number: $number"
  312. case Person(name, number) => s"Random person's number: $number"
  313. }
  314. /////////////////////////////////////////////////
  315. // 7\. 函数式编程
  316. /////////////////////////////////////////////////
  317. // Scala 允许方法和函数作为其他方法和函数的参数和返回值。
  318. val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数
  319. List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素
  320. // 匿名函数可以被使用来代替有命名的函数:
  321. List(1, 2, 3) map (x => x + 10)
  322. // 如果匿名函数只有一个参数可以用下划线作为变量
  323. List(1, 2, 3) map (_ + 10)
  324. // 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线
  325. List("Dom", "Bob", "Natalia") foreach println
  326. // 组合子
  327. // 译注: val sq: Int => Int = x => x * x
  328. s.map(sq)
  329. val sSquared = s. map(sq)
  330. sSquared.filter(_ < 10)
  331. sSquared.reduce (_+_)
  332. // filter 函数接受一个 predicate (函数根据条件 A 返回 Boolean)并选择
  333. // 所有满足 predicate 的元素
  334. List(1, 2, 3) filter (_ > 2) // List(3)
  335. case class Person(name:String, age:Int)
  336. List(
  337. Person(name = "Dom", age = 23),
  338. Person(name = "Bob", age = 30)
  339. ).filter(_.age > 25) // List(Person("Bob", 30))
  340. // Scala 的 foreach 方法定义在某些集合中,接受一个函数并返回 Unit (void 方法)
  341. // 另请参见:
  342. // http://www.scala-lang.org/api/current/index.html#scala.collection.IterableLike@foreach(f:A=>Unit):Unit
  343. val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
  344. aListOfNumbers foreach (x => println(x))
  345. aListOfNumbers foreach println
  346. // For 推导式
  347. for { n <- s } yield sq(n)
  348. val nSquared2 = for { n <- s } yield sq(n)
  349. for { n <- nSquared2 if n < 10 } yield n
  350. for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
  351. /* 注意,这些不是 for 循环,for 循环的语义是‘重复’,然而 for 推导式定义
  352. 两个数据集合的关系。 */
  353. /////////////////////////////////////////////////
  354. // 8\. 隐式转换
  355. /////////////////////////////////////////////////
  356. /* 警告 警告: 隐式转换是 Scala 中一套强大的特性,因此容易被滥用。
  357. * Scala 初学者在理解它们的工作原理和最佳实践之前,应抵制使用它的诱惑。
  358. * 我们加入这一章节仅因为它们在 Scala 的库中太过常见,导致没有用隐式转换的库
  359. * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。
  360. */
  361. // 可以通过 "implicit" 声明任何值(val, 函数,对象等)为隐式值,
  362. // 请注意这些例子中,我们用到第5部分的 Dog 类。
  363. implicit val myImplicitInt = 100
  364. implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed)
  365. // implicit 关键字本身不改变值的行为,所以上面的值可以照常使用。
  366. myImplicitInt + 2 // => 102
  367. myImplicitFunction("Pitbull").breed // => "Golden Pitbull"
  368. // 区别在于,当另一段代码“需要”隐式值时,这些值现在有资格作为隐式值。
  369. // 一种情况是隐式函数参数。
  370. def sendGreetings(toWhom: String)(implicit howMany: Int) =
  371. s"Hello $toWhom, $howMany blessings to you and yours!"
  372. // 如果提供值给 “howMany”,函数正常运行
  373. sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!"
  374. // 如果省略隐式参数,会传一个和参数类型相同的隐式值,
  375. // 在这个例子中, 是 “myImplicitInt":
  376. sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
  377. // 隐式的函数参数使我们可以模拟其他函数式语言的 type 类(type classes)。
  378. // 它经常被用到所以有特定的简写。这两行代码是一样的:
  379. def foo[T](implicit c: C[T]) = ...
  380. def foo[T : C] = ...
  381. // 编译器寻找隐式值另一种情况是你调用方法时
  382. // obj.method(...)
  383. // 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果有一个参数类型为 A
  384. // 返回值类型为 B 的隐式转换,obj 的类型是 A,B 有一个方法叫 "method" ,这样
  385. // 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做:
  386. "Retriever".breed // => "Golden Retriever"
  387. "Sheperd".bark // => "Woof, woof!"
  388. // 这里字符串先被上面的函数转换为 Dog 对象,然后调用相应的方法。
  389. // 这是相当强大的特性,但再次提醒,请勿轻率使用。
  390. // 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解
  391. // 你正在做什么否则不要使用。
  392. /////////////////////////////////////////////////
  393. // 9\. 杂项
  394. /////////////////////////////////////////////////
  395. // 导入类
  396. import scala.collection.immutable.List
  397. // 导入所有子包
  398. import scala.collection.immutable._
  399. // 一条语句导入多个类
  400. import scala.collection.immutable.{List, Map}
  401. // 使用 ‘=>’ 对导入进行重命名
  402. import scala.collection.immutable.{ List => ImmutableList }
  403. // 导入所有类,排除其中一些。下面的语句排除了 Map 和 Set:
  404. import scala.collection.immutable.{Map => _, Set => _, _}
  405. // 在 Scala 文件用 object 和单一的 main 方法定义程序入口:
  406. object Application {
  407. def main(args: Array[String]): Unit = {
  408. // stuff goes here.
  409. }
  410. }
  411. // 文件可以包含多个 class 和 object,用 scalac 编译源文件
  412. // 输入和输出
  413. // 按行读文件
  414. import scala.io.Source
  415. for(line <- Source.fromFile("myfile.txt").getLines())
  416. println(line)
  417. // 用 Java 的 PrintWriter 写文件
  418. val writer = new PrintWriter("myfile.txt")
  419. writer.write("Writing line for line" + util.Properties.lineSeparator)
  420. writer.write("Another line here" + util.Properties.lineSeparator)
  421. writer.close()

更多的资源

为没耐心的人准备的 Scala

Twitter Scala school

The Scala documentation

在浏览器尝试 Scala

加入 Scala 用户组


还没有评论.