https://learnxinyminutes.com/docs/zh-cn/scala-cn/
/*
REPL(读取-求值-输出循环 Read-Eval-Print Loop)
*/
进一步学习,官方文档
https://docs.scala-lang.org/
1. 基础
// 单行注释开始于两个斜杠
/* 多行知识
*/
//通过var或者val来声明变量,val声明是不可变的,var声明是可修改的
1 + 7
/* 上行的结果是:
scala> 1 + 7
res29: Int = 8
这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8
注意 “res29” 是一个连续生成的变量名,用以存储您输入的表达式结果,
您看到的输出可能不一样。
*/
// String 有常见的 Java 字符串方法
“hello world”.length
“hello world”.substring(2,6)
“hello world”.replace(“C”,“3”)
// 字符串改写:留意前缀"s"
var n = 45
s"We have $n apples" // => “We have 45 apples”
var a = Array(11, 9, 6)
s"My second daughter is ${a(0) - a(2)} years old." // My second daughter is 5 years old.
// f 为格式化字符串
f"Square root of 122: ${math.sqrt(122)}%1.4f"
res9: String = Square root of 122: 11.0454
// 未处理的字符串,忽略特殊字符
raw"New line feed: \n. Carriage return: \r."
// 三个双引号可以使字符串跨越多行,并包含引号
val html = """<form id="daform">
<p>Press belo', Joe</p>
<input type="submit">
</form>"""
// 正则表达式
// val () =
val input = “Enjoying this apple 2.17 times today”
val pattern = “”".apple ([\d.]+) times .""".r
val pattern(amountText) = input
=> String = 2.17
2. 函数
// def functionName(args…): ReturnType = {…}
def sumOfSquares(x: Int, y: Int): Int = {
val x2 = x * x
val y2 = y * y
x2 + y2
}
// 单行可以省略括号
def sumOfSquaresShort(x : Int, y: Int): Int = xx + yy
sumOfSquaresShort(3, 4)
// 默认参数
def addWithDefault(x: Int, y: Int = 5) &#