Scala数组的定义

本文深入探讨Scala中的数组定义与操作,包括使用Array类创建数组、元素的读写、数组的映射(map)与扁平化(flatten)操作,以及如何进行WordCount统计。通过实例演示了Scala数组的灵活性和强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义方式,可以new

scala> val arr = new Array[Int](3)
arr: Array[Int] = Array(0, 0, 0)

scala> arr[0] = 100
<console>:1: error: identifier expected but integer literal found.
arr[0] = 100
    ^

在scala中用()

scala> arr(0) = 100

scala> arr(0)
res5: Int = 100

定义方式2:

scala> val arr = Array[Int](1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)

scala> arr(1) = 100;

内容可变,长度不可变

scala> arr += 8
<console>:13: error: value += is not a member of Array[Int]
       arr += 8
           ^

scala> fx = (x: Int) => x * 10
<console>:13: error: not found: value fx
val $ires0 = fx
             ^
<console>:11: error: not found: value fx
       fx = (x: Int) => x * 10
       ^

//arr经过map映射操作之后,会返回一个新的数组

scala> val fx = (x: Int) => x * 10
fx: Int => Int = <function1>

scala> arr.map(fx)
res8: Array[Int] = Array(10, 1000, 30, 40, 50)

scala> arr
res9: Array[Int] = Array(1, 100, 3, 4, 5)

 

 

//arr经过map映射操作之后,会返回一个新的数组

scala> val fx = (x: Int) => x * 10
fx: Int => Int = <function1>

scala> arr.map(fx)
res8: Array[Int] = Array(10, 1000, 30, 40, 50)

scala> arr
res9: Array[Int] = Array(1, 100, 3, 4, 5)

 

flatten:扁平化

scala> val arr = Array("hello you hello me","hello nimoo hello jim")
arr: Array[String] = Array(hello you hello me, hello nimoo hello jim)

scala> arr.map(_.split(" "))
res10: Array[Array[String]] = Array(Array(hello, you, hello, me), Array(hello, nimoo, hello, jim))

scala> arr.map(_.split(" ")).faltten
<console>:13: error: value faltten is not a member of Array[Array[String]]
       arr.map(_.split(" ")).faltten
                             ^

scala> arr.map(_.split(" ")).flatten
res12: Array[String] = Array(hello, you, hello, me, hello, nimoo, hello, jim)

map+ flatten

scala> arr.flatMap(_.split(" "))
res13: Array[String] = Array(hello, you, hello, me, hello, nimoo, hello, jim)

 

求WordCount

scala> arr
res16: Array[String] = Array(hello you hello me, hello nimoo hello jim)

scala> arr.flatMap(_.split(" ")).groupBy(x => x)
res17: scala.collection.immutable.Map[String,Array[String]] = Map(nimoo -> Array(nimoo), you -> Array(you), jim -> Array(jim), me -> Array(me), hello -> Array(hello, hello, hello, hello))

scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length)
res18: scala.collection.immutable.Map[String,Int] = Map(nimoo -> 1, you -> 1, jim -> 1, me -> 1, hello -> 4)

scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList
res19: List[(String, Int)] = List((nimoo,1), (you,1), (jim,1), (me,1), (hello,4))

scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => x._2)
res20: List[(String, Int)] = List((nimoo,1), (you,1), (jim,1), (me,1), (hello,4))

scala> arr.flatMap(_.split(" ")).groupBy(x => x).mapValues(_.length).toList.sortBy(x => - x._2)
res21: List[(String, Int)] = List((hello,4), (nimoo,1), (you,1), (jim,1), (me,1))

以下是整合了单例对象讲解的完整博客内容: # Scala实现手机号码类型识别:从C语言基础到实战 作为学过C语言的零基础学习者,我们来看看Scala中如何实现手机号码类型识别。本文会结合C语言基础,对比介绍Scala数组、函数与单例对象语法,再完成功能实现。 ## 一、Scala数组基础(对比C语言) 在C语言中,数组是固定长度、同类型元素的集合,比如 `int arr[5];`。而Scala数组: - **不可变特性**:默认创建后元素不可变(修改需重新赋值)。 - **定义方式**:通过 `Array` 类创建。 示例: ```scala // C语言数组定义 // int cArray[3] = {1, 2, 3}; // Scala数组定义 val scalaArray = Array(1, 2, 3) // 自动推断类型为Array[Int] ``` ## 二、Scala函数定义语法(对比C语言) C语言中,函数定义会声明返回值类型,如 `void func() { ... }` 表示无返回值。Scala函数语法更明确: - **`def` 关键字**:Scala用 `def` 定义函数。 - **返回类型声明**:Scala强制显式声明返回类型(少数递归场景除外)。无有意义返回值时,用 `Unit`(类似C语言的 `void`)。 - **函数定义结构**: ```scala def 函数名(参数: 参数类型): 返回类型 = { // 函数体 } ``` 例如: ```scala def identify(segment: String): Unit = { // 函数体逻辑,无实际返回值,用Unit } ``` ## 三、Scala单例对象(对比C语言全局函数) 在C语言中,全局函数可直接调用(如 `printf`)。Scala通过 **单例对象** 实现类似功能,但更强调封装性: - **`object` 关键字**:定义全局唯一的单例对象,无需实例化,直接通过名称访问成员。 - **程序入口**:Scala程序的入口 `main` 方法必须定义在单例对象中。 示例: ```scala object PhoneNumberIdentify { // 单例对象内的方法可直接调用 def identify(segment: String): Unit = { println("识别逻辑") } // 程序入口,Scala程序从main方法启动 def main(args: Array[String]): Unit = { identify("133") // 直接调用单例对象内的方法 } } ``` **与C语言的对比**: - C语言的全局函数可直接调用(如 `func()`),Scala通过单例对象的名称调用(如 `PhoneNumberIdentify.identify("133")`)。 - 若方法定义在单例对象内部(与 `main` 平级),可省略对象名直接调用(如示例中的 `identify("133")`)。 ## 四、手机号码类型识别实现 ### 1. 准备号段数组 ```scala val telecomSegments = Array("133", "153", "177") val mobileSegments = Array("134", "135", "136") val unicomSegments = Array("130", "131", "132") ``` ### 2. 定义识别函数(在单例对象内) ```scala def identify(segment: String): Unit = { if (telecomSegments.contains(segment)) { println("中国电信") } else if (mobileSegments.contains(segment)) { println("中国移动") } else if (unicomSegments.contains(segment)) { println("中国联通") } else { println("暂不支持") } } ``` ### 3. 主方法调用 ```scala def main(args: Array[String]): Unit = { identify("133") // 直接调用单例对象内的方法 } ``` ## 五、代码完整示例 ```scala object PhoneNumberIdentify { // 定义各运营商号段数组 val telecomSegments = Array("133", "153", "177") val mobileSegments = Array("134", "135", "136") val unicomSegments = Array("130", "131", "132") // 定义识别函数(与main平级) def identify(segment: String): Unit = { if (telecomSegments.contains(segment)) { println("这个号码是属于中国电信的") } else if (mobileSegments.contains(segment)) { println("这个号码是属于中国移动的") } else if (unicomSegments.contains(segment)) { println("这个号码是属于中国联通的") } else { println("暂不支持该号段识别") } } // 程序入口 def main(args: Array[String]): Unit = { identify("133") // 直接调用单例对象内的方法 } } ``` ## 六、总结 通过案例,我们掌握了Scala数组、函数与单例对象语法: 1. **数组**:Scala默认不可变,通过 `Array` 类创建,与C语言数组逻辑一致。 2. **函数**:强制声明返回类型,`Unit` 对应C语言的 `void`。 3. **单例对象**:封装全局逻辑,替代C语言的全局函数,提升代码组织性。 Scala语法虽与C语言有差异,但核心逻辑相通,结合C语言基础理解更轻松!帮我整理成博客的格式
最新发布
03-08
### Scala 中 `Array` 的 `apply` 方法 在 Scala 中,`Array` 是一种固定大小的序列集合。通过 `apply` 方法可以从数组中获取特定索引位置上的元素[^1]。 #### 获取单个元素 下面展示如何利用 `apply` 方法访问数组中的某个具体元素: ```scala val numbers = Array(10, 20, 30, 40, 50) println(s"The element at index 2 is ${numbers.apply(2)}") // 输出 The element at index 2 is 30 ``` 这段代码创建了一个名为 `numbers` 的整型数组,并使用 `apply` 方法读取索引为 2 处的值(即第三个元素),结果为 30。 #### 结合其他函数一起工作 除了单独用于检索数据外,`apply` 还经常与其他高阶函数配合使用来处理复杂逻辑: ```scala val data = Array("apple", "banana", "orange") // 找到长度大于等于6的第一个字符串并打印出来 data.find(_.length >= 6).foreach(word => println(s"Found word with length>=6: $word")) ``` 在这个例子中虽然没有直接看到 `apply` 函数的应用,但实际上当调用像 `find()` 或者 `foreach()` 等方法时内部都会涉及到对各个元素的操作——这背后就依赖于 `apply` 来完成实际的数据存取操作。 #### 创建新数组 值得注意的是,在某些情况下也可以借助 `apply` 构造新的数组实例。不过这种方式更常见于可变集合类型如 `Buffer` 或者不可变类型的工厂方法里;对于基本类型的 `Array` 则通常采用字面量形式定义或通过 `ofDim` 工厂方法初始化。 ```scala import scala.collection.mutable.ArrayBuffer val buffer = ArrayBuffer[Int]() buffer += (1 to 5): _* // 添加一系列数值至缓冲区 println(buffer.toArray) // 将其转换成普通数组输出 [1,2,3,4,5] ``` 尽管上述示例主要展示了关于 `ArrayBuffer` 的应用,但是从中可以看出不同容器间相互转化的过程中同样离不开 `apply` 的作用机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值