Scala基础练习

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) &#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值