Scala 入门指南

打印 上一主题 下一主题

主题 1604|帖子 1604|积分 4812

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Scala 入门指南

目录



  • 简介
  • 环境搭建
  • 基础语法
  • 面向对象编程
  • 函数式编程
  • 聚集
  • 模式匹配
  • 特质
  • 隐式转换
  • 并发编程
  • 与 Java 互操纵
  • 最佳实践
  • 常见题目
简介

Scala 是一种多范式编程语言,联合了面向对象编程和函数式编程的特性。它运行在 JVM 上,与 Java 完全兼容,并且可以调用 Java 库。
Scala 的重要特性



  • 面向对象和函数式编程的联合
  • 静态范例体系
  • 范例推断
  • 模式匹配
  • 高阶函数
  • 不可变数据结构
  • 并发编程支持
  • 与 Java 互操纵
环境搭建

1. 安装 JDK

Scala 需要 JDK 环境,保举使用 JDK 8 或更高版本。
  1. # 检查 Java 版本
  2. java -version
复制代码
2. 安装 Scala

方法一:使用 SDKMAN(保举)

  1. # 安装 SDKMAN
  2. curl -s "https://get.sdkman.io" | bash
  3. source "$HOME/.sdkman/bin/sdkman-init.sh"
  4. # 安装 Scala
  5. sdk install scala
复制代码
方法二:直接下载安装

从 Scala 官网 下载安装包并安装。
3. 安装 IDE

保举使用 IntelliJ IDEA 或 VS Code 配合 Scala 插件。
IntelliJ IDEA


  • 下载并安装 IntelliJ IDEA
  • 安装 Scala 插件:File → Settings → Plugins → 搜索 “Scala” → 安装
  • 重启 IDE
VS Code


  • 安装 VS Code
  • 安装 “Scala (Metals)” 插件
  • 安装 “Scala Syntax (official)” 插件
4. 验证安装

  1. # 检查 Scala 版本
  2. scala -version
  3. # 启动 Scala REPL
  4. scala
复制代码
基础语法

1. 变量和常量

  1. // 变量(可变)
  2. var x = 10
  3. x = 20  // 可以修改
  4. // 常量(不可变)
  5. val y = 30
  6. // y = 40  // 编译错误,不能修改
  7. // 类型声明(可选)
  8. val name: String = "Scala"
  9. var age: Int = 25
复制代码
2. 基本数据范例

  1. // 数值类型
  2. val byte: Byte = 127
  3. val short: Short = 32767
  4. val int: Int = 2147483647
  5. val long: Long = 9223372036854775807L
  6. val float: Float = 3.14f
  7. val double: Double = 3.141592653589793
  8. // 字符
  9. val char: Char = 'A'
  10. // 布尔值
  11. val boolean: Boolean = true
  12. // 字符串
  13. val string: String = "Hello, Scala!"
复制代码
3. 字符串操纵

  1. val name = "Scala"
  2. val version = 3.0
  3. // 字符串插值
  4. val message = s"$name version $version"
  5. val message2 = s"${name.toUpperCase} version ${version + 0.1}"
  6. // 多行字符串
  7. val multiline = """
  8.   |This is a
  9.   |multiline
  10.   |string
  11.   |""".stripMargin
复制代码
4. 运算符

  1. // 算术运算符
  2. val a = 10
  3. val b = 3
  4. val sum = a + b
  5. val diff = a - b
  6. val product = a * b
  7. val quotient = a / b
  8. val remainder = a % b
  9. // 比较运算符
  10. val isEqual = a == b
  11. val isNotEqual = a != b
  12. val isGreater = a > b
  13. val isLess = a < b
  14. val isGreaterOrEqual = a >= b
  15. val isLessOrEqual = a <= b
  16. // 逻辑运算符
  17. val p = true
  18. val q = false
  19. val and = p && q
  20. val or = p || q
  21. val not = !p
复制代码
5. 条件语句

  1. // if-else 语句
  2. val age = 20
  3. val status = if (age >= 18) "成年" else "未成年"
  4. // 多分支 if-else
  5. val grade = 85
  6. val level = if (grade >= 90) "A"
  7.            else if (grade >= 80) "B"
  8.            else if (grade >= 70) "C"
  9.            else if (grade >= 60) "D"
  10.            else "F"
复制代码
6. 循环

  1. // for 循环
  2. for (i <- 1 to 5) {
  3.   println(i)
  4. }
  5. // 带过滤器的 for 循环
  6. for (i <- 1 to 10 if i % 2 == 0) {
  7.   println(i)
  8. }
  9. // for 推导式
  10. val squares = for (i <- 1 to 5) yield i * i
  11. // while 循环
  12. var i = 1
  13. while (i <= 5) {
  14.   println(i)
  15.   i += 1
  16. }
  17. // do-while 循环
  18. var j = 1
  19. do {
  20.   println(j)
  21.   j += 1
  22. } while (j <= 5)
复制代码
面向对象编程

1. 类定义

  1. // 简单类
  2. class Person {
  3.   var name: String = ""
  4.   var age: Int = 0
  5.   
  6.   def sayHello(): Unit = {
  7.     println(s"Hello, my name is $name and I am $age years old.")
  8.   }
  9. }
  10. // 主构造函数
  11. class Person(val name: String, var age: Int) {
  12.   def sayHello(): Unit = {
  13.     println(s"Hello, my name is $name and I am $age years old.")
  14.   }
  15. }
  16. // 辅助构造函数
  17. class Person {
  18.   var name: String = ""
  19.   var age: Int = 0
  20.   
  21.   def this(name: String) {
  22.     this()
  23.     this.name = name
  24.   }
  25.   
  26.   def this(name: String, age: Int) {
  27.     this(name)
  28.     this.age = age
  29.   }
  30. }
复制代码
2. 对象(单例)

  1. // 单例对象
  2. object Singleton {
  3.   def sayHello(): Unit = {
  4.     println("Hello from singleton!")
  5.   }
  6. }
  7. // 伴生对象
  8. class Person(val name: String) {
  9.   def sayHello(): Unit = {
  10.     println(s"Hello, my name is $name")
  11.   }
  12. }
  13. object Person {
  14.   def apply(name: String): Person = new Person(name)
  15.   
  16.   def unapply(person: Person): Option[String] = Some(person.name)
  17. }
复制代码
3. 继承

  1. // 基类
  2. class Animal(val name: String) {
  3.   def makeSound(): Unit = {
  4.     println("Some sound")
  5.   }
  6. }
  7. // 子类
  8. class Dog(name: String) extends Animal(name) {
  9.   override def makeSound(): Unit = {
  10.     println("Woof!")
  11.   }
  12. }
  13. // 抽象类
  14. abstract class Shape {
  15.   def area(): Double
  16.   def perimeter(): Double
  17. }
  18. class Circle(radius: Double) extends Shape {
  19.   def area(): Double = Math.PI * radius * radius
  20.   def perimeter(): Double = 2 * Math.PI * radius
  21. }
复制代码
4. 封装

  1. class BankAccount {
  2.   private var balance = 0.0
  3.   
  4.   def deposit(amount: Double): Unit = {
  5.     if (amount > 0) {
  6.       balance += amount
  7.     }
  8.   }
  9.   
  10.   def withdraw(amount: Double): Boolean = {
  11.     if (amount > 0 && amount <= balance) {
  12.       balance -= amount
  13.       true
  14.     } else {
  15.       false
  16.     }
  17.   }
  18.   
  19.   def getBalance: Double = balance
  20. }
复制代码
函数式编程

1. 函数定义

  1. // 基本函数
  2. def add(x: Int, y: Int): Int = x + y
  3. // 无参数函数
  4. def getCurrentTime(): Long = System.currentTimeMillis()
  5. // 默认参数
  6. def greet(name: String, greeting: String = "Hello"): String = {
  7.   s"$greeting, $name!"
  8. }
  9. // 命名参数
  10. def createPerson(name: String, age: Int, city: String): String = {
  11.   s"$name is $age years old and lives in $city"
  12. }
  13. val person = createPerson(name = "Alice", age = 30, city = "New York")
复制代码
2. 高阶函数

  1. // 函数作为参数
  2. def applyOperation(x: Int, f: Int => Int): Int = f(x)
  3. val double = (x: Int) => x * 2
  4. val square = (x: Int) => x * x
  5. val result1 = applyOperation(5, double)  // 10
  6. val result2 = applyOperation(5, square)  // 25
  7. // 函数作为返回值
  8. def multiplier(factor: Int): Int => Int = {
  9.   (x: Int) => x * factor
  10. }
  11. val multiplyByTwo = multiplier(2)
  12. val result3 = multiplyByTwo(5)  // 10
复制代码
3. 匿名函数

  1. // 基本匿名函数
  2. val add = (x: Int, y: Int) => x + y
  3. // 简写形式
  4. val numbers = List(1, 2, 3, 4, 5)
  5. val doubled = numbers.map(x => x * 2)
  6. val evenNumbers = numbers.filter(_ % 2 == 0)
  7. // 部分应用函数
  8. val sum = (a: Int, b: Int, c: Int) => a + b + c
  9. val addOneAndTwo = sum(1, 2, _)
  10. val result = addOneAndTwo(3)  // 6
复制代码
4. 柯里化

  1. // 柯里化函数
  2. def add(x: Int)(y: Int): Int = x + y
  3. val addOne = add(1)_
  4. val result = addOne(5)  // 6
  5. // 非柯里化转柯里化
  6. def nonCurriedAdd(x: Int, y: Int): Int = x + y
  7. def curriedAdd = (nonCurriedAdd _).curried
复制代码
聚集

1. 不可变聚集

  1. // List
  2. val list = List(1, 2, 3, 4, 5)
  3. val first = list.head
  4. val rest = list.tail
  5. val newList = 0 :: list  // 在头部添加元素
  6. val concatenated = list ++ List(6, 7)  // 连接列表
  7. // Set
  8. val set = Set(1, 2, 3, 3, 4, 4, 5)  // 结果为 Set(1, 2, 3, 4, 5)
  9. val contains = set.contains(3)  // true
  10. val newSet = set + 6  // 添加元素
  11. // Map
  12. val map = Map("a" -> 1, "b" -> 2, "c" -> 3)
  13. val value = map("a")  // 1
  14. val valueOrDefault = map.getOrElse("d", 0)  // 0
  15. val newMap = map + ("d" -> 4)  // 添加键值对
复制代码
2. 可变聚集

  1. import scala.collection.mutable
  2. // 可变 ListBuffer
  3. val buffer = mutable.ListBuffer(1, 2, 3)
  4. buffer += 4  // 添加元素
  5. buffer -= 2  // 移除元素
  6. // 可变 Set
  7. val mutableSet = mutable.Set(1, 2, 3)
  8. mutableSet += 4  // 添加元素
  9. mutableSet -= 2  // 移除元素
  10. // 可变 Map
  11. val mutableMap = mutable.Map("a" -> 1, "b" -> 2)
  12. mutableMap("c") = 3  // 添加或更新键值对
  13. mutableMap -= "a"  // 移除键值对
复制代码
3. 聚集操纵

  1. val numbers = List(1, 2, 3, 4, 5)
  2. // 映射
  3. val doubled = numbers.map(_ * 2)  // List(2, 4, 6, 8, 10)
  4. // 过滤
  5. val evenNumbers = numbers.filter(_ % 2 == 0)  // List(2, 4)
  6. // 扁平化
  7. val nestedList = List(List(1, 2), List(3, 4), List(5))
  8. val flattened = nestedList.flatten  // List(1, 2, 3, 4, 5)
  9. // 扁平映射
  10. val flatMapped = nestedList.flatMap(identity)  // List(1, 2, 3, 4, 5)
  11. // 折叠
  12. val sum = numbers.foldLeft(0)(_ + _)  // 15
  13. val product = numbers.foldRight(1)(_ * _)  // 120
  14. // 归约
  15. val max = numbers.reduce((a, b) => if (a > b) a else b)  // 5
复制代码
模式匹配

1. 基本模式匹配

  1. def matchNumber(x: Int): String = x match {
  2.   case 0 => "zero"
  3.   case 1 => "one"
  4.   case 2 => "two"
  5.   case _ => "many"
  6. }
  7. // 匹配多个值
  8. def matchMultiple(x: Int): String = x match {
  9.   case 0 | 1 | 2 => "small"
  10.   case 3 | 4 | 5 => "medium"
  11.   case _ => "large"
  12. }
复制代码
2. 范例模式匹配

  1. def matchType(x: Any): String = x match {
  2.   case s: String => s"String: $s"
  3.   case i: Int => s"Integer: $i"
  4.   case d: Double => s"Double: $d"
  5.   case _ => "Unknown type"
  6. }
复制代码
3. 序列模式匹配

  1. def matchList(list: List[Int]): String = list match {
  2.   case Nil => "Empty list"
  3.   case List(x) => s"Single element: $x"
  4.   case List(x, y) => s"Two elements: $x and $y"
  5.   case x :: rest => s"First element: $x, rest: $rest"
  6. }
复制代码
4. 样例类模式匹配

  1. // 定义样例类
  2. case class Person(name: String, age: Int)
  3. case class Dog(name: String, breed: String)
  4. // 模式匹配
  5. def matchPerson(person: Any): String = person match {
  6.   case Person(name, age) => s"Person: $name, $age years old"
  7.   case Dog(name, breed) => s"Dog: $name, breed: $breed"
  8.   case _ => "Unknown"
  9. }
复制代码
特质

1. 基本特质

  1. // 定义特质
  2. trait Speaker {
  3.   def speak(): String
  4. }
  5. // 实现特质
  6. class Dog extends Speaker {
  7.   def speak(): String = "Woof!"
  8. }
  9. class Cat extends Speaker {
  10.   def speak(): String = "Meow!"
  11. }
复制代码
2. 带实现的特质

  1. trait Animal {
  2.   def name: String
  3.   def makeSound(): String
  4.   
  5.   def description(): String = s"$name says ${makeSound()}"
  6. }
  7. class Dog(val name: String) extends Animal {
  8.   def makeSound(): String = "Woof!"
  9. }
  10. class Cat(val name: String) extends Animal {
  11.   def makeSound(): String = "Meow!"
  12. }
复制代码
3. 特质叠加

  1. trait Logging {
  2.   def log(msg: String): Unit = println(s"Log: $msg")
  3. }
  4. trait TimestampLogging extends Logging {
  5.   override def log(msg: String): Unit = {
  6.     val timestamp = java.time.Instant.now()
  7.     super.log(s"[$timestamp] $msg")
  8.   }
  9. }
  10. trait ShortLogging extends Logging {
  11.   override def log(msg: String): Unit = {
  12.     if (msg.length > 20) {
  13.       super.log(msg.substring(0, 20) + "...")
  14.     } else {
  15.       super.log(msg)
  16.     }
  17.   }
  18. }
  19. // 特质叠加顺序从右到左
  20. class MyClass extends ShortLogging with TimestampLogging {
  21.   def doSomething(): Unit = {
  22.     log("This is a very long message that should be shortened")
  23.   }
  24. }
复制代码
隐式转换

1. 基本隐式转换

  1. // 定义隐式转换
  2. implicit def intToString(x: Int): String = x.toString
  3. // 使用隐式转换
  4. val str: String = 42  // 自动转换为 "42"
复制代码
2. 隐式参数

  1. // 定义带有隐式参数的函数
  2. def greet(name: String)(implicit greeting: String): String = {
  3.   s"$greeting, $name!"
  4. }
  5. // 定义隐式值
  6. implicit val defaultGreeting: String = "Hello"
  7. // 使用隐式参数
  8. val message = greet("Alice")  // "Hello, Alice!"
  9. // 显式提供参数
  10. val customMessage = greet("Bob")("Hi")  // "Hi, Bob!"
复制代码
3. 范例类

  1. // 定义类型类
  2. trait Show[A] {
  3.   def show(a: A): String
  4. }
  5. // 为 Int 实现类型类
  6. implicit val intShow: Show[Int] = new Show[Int] {
  7.   def show(a: Int): String = a.toString
  8. }
  9. // 为 String 实现类型类
  10. implicit val stringShow: Show[String] = new Show[String] {
  11.   def show(a: String): String = a
  12. }
  13. // 使用类型类
  14. def printValue[A](a: A)(implicit show: Show[A]): Unit = {
  15.   println(show.show(a))
  16. }
  17. printValue(42)  // 打印 "42"
  18. printValue("Hello")  // 打印 "Hello"
复制代码
并发编程

1. Future

  1. import scala.concurrent.Future
  2. import scala.concurrent.ExecutionContext.Implicits.global
  3. // 创建 Future
  4. val future = Future {
  5.   Thread.sleep(1000)
  6.   42
  7. }
  8. // 处理 Future 结果
  9. future.onComplete {
  10.   case scala.util.Success(value) => println(s"Result: $value")
  11.   case scala.util.Failure(exception) => println(s"Error: ${exception.getMessage}")
  12. }
  13. // 使用 map 和 flatMap
  14. val futureResult = future.map(_ * 2).map(_.toString)
  15. // 使用 for 推导式
  16. val combinedFuture = for {
  17.   a <- Future { 10 }
  18.   b <- Future { 20 }
  19. } yield a + b
复制代码
2. Actor 模型(Akka)

  1. import akka.actor.{Actor, ActorSystem, Props}
  2. // 定义 Actor
  3. class Greeter extends Actor {
  4.   def receive = {
  5.     case "hello" => println("Hello, world!")
  6.     case msg: String => println(s"Received: $msg")
  7.     case _ => println("Unknown message")
  8.   }
  9. }
  10. // 创建 Actor 系统
  11. val system = ActorSystem("MySystem")
  12. val greeter = system.actorOf(Props[Greeter], "greeter")
  13. // 发送消息
  14. greeter ! "hello"
  15. greeter ! "How are you?"
  16. // 关闭系统
  17. system.terminate()
复制代码
与 Java 互操纵

1. 调用 Java 代码

  1. // 导入 Java 类
  2. import java.util.Date
  3. // 创建 Java 对象
  4. val date = new Date()
  5. println(date)
  6. // 调用 Java 方法
  7. val list = new java.util.ArrayList[String]()
  8. list.add("Scala")
  9. list.add("Java")
  10. println(list)
复制代码
2. Java 调用 Scala 代码

  1. // Scala 类
  2. class ScalaClass(val name: String) {
  3.   def greet(): String = s"Hello from $name"
  4. }
  5. // 伴生对象
  6. object ScalaClass {
  7.   def create(name: String): ScalaClass = new ScalaClass(name)
  8. }
复制代码
  1. // Java 代码
  2. ScalaClass scala = ScalaClass.create("Scala");
  3. String greeting = scala.greet();
  4. System.out.println(greeting);
复制代码
最佳实践

1. 代码风格



  • 使用驼峰定名法
  • 类名首字母大写
  • 方法名首字母小写
  • 使用有意义的变量名
  • 得当添加注释
2. 函数式编程原则



  • 优先使用不可变数据
  • 使用纯函数
  • 克制副作用
  • 使用高阶函数和组合
3. 错误处理

  1. // 使用 Option
  2. def divide(a: Int, b: Int): Option[Int] = {
  3.   if (b != 0) Some(a / b) else None
  4. }
  5. // 使用 Try
  6. import scala.util.Try
  7. def safeDivide(a: Int, b: Int): Try[Int] = Try(a / b)
  8. // 使用 Either
  9. def parseNumber(s: String): Either[String, Int] = {
  10.   try {
  11.     Right(s.toInt)
  12.   } catch {
  13.     case _: NumberFormatException => Left(s"Invalid number: $s")
  14.   }
  15. }
复制代码
常见题目

1. 编译错误



  • 范例不匹配
  • 缺少分号
  • 括号不匹配
  • 导入错误
2. 运行时错误



  • 空指针异常
  • 范例转换错误
  • 并发题目
3. 性能题目



  • 内存泄漏
  • 过分使用递归
  • 聚集操纵效率
4. 调试技巧



  • 使用 println 调试
  • 使用 IDE 调试器
  • 使用日志框架
  • 单元测试
学习资源



  • Scala 官方文档
  • Scala School
  • Scala 编程(册本)
  • Scala 函数式编程(册本)
  • Coursera Scala 课程

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户国营

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表