Scala中一些符号组合用法的总结

本篇总结一些符号的组合用法,未完待续。

符号“:”用法

用法1:构造List

示例:

1
2
3
4
scala> val l0 = 1::2::3::4::Nil
l0: List[Int] = List(1, 2, 3, 4)
scala>

用法1:元素与List连接

示例:

1
2
3
4
5
6
7
8
9
10
11
12
scala> val l = List(1,2,3,4)
l: List[Int] = List(1, 2, 3, 4)
scala> val ll = 5::l
ll: List[Int] = List(5, 1, 2, 3, 4)
scala> val ll = l::5
<console>:13: error: value :: is not a member of Int
val ll = l::5
^
scala>

用法2:组合成“:::”来拼接List

用来作为List的拼接:

1
2
3
4
5
6
7
scala> val l2 = List(9,8,7,6)
l2: List[Int] = List(9, 8, 7, 6)
scala> l:::l2
res18: List[Int] = List(1, 2, 3, 4, 9, 8, 7, 6)
scala>

符号“_”用法

用法1:“_*”

将参数作为序列进行操作,用一个实例进行说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
scala> def sum(args: Int*): Int = {
| var total: Int = 0
| for(arg <- args) {
| total = total + arg
| }
| total
| }
sum: (args: Int*)Int
scala> val s = sum(1 to 5: _*)
s: Int = 15
scala>

1 to 5: _*足以说明问题;

用法2:导包

类似Java中的*:import java.util._

用法3:变量初始化默认值

var i: String = _

用法4:访问元组元素

1
2
3
4
5
6
7
scala> val a = ( 1 -> "nihao", 2 -> "nihao01", 3-> "nihao03")
a: ((Int, String), (Int, String), (Int, String)) = ((1,nihao),(2,nihao01),(3,nihao03))
scala> a._1
res10: (Int, String) = (1,nihao)
scala>

下划线后面跟的数字表示元组中从左数第几个出现的元素;

用法5:占位符

利用类型推导极简代码,比如将匿名函数赋值给变量:

1
2
3
4
scala> val a: Int => Int = _ * 2
a: Int => Int = <function1>
scala>

此种方法特别适合于已知返回值的类型的情况;

用法6:作为通配符为函数赋值

1
2
3
4
5
6
7
8
9
10
scala> def add(x: Int) = x * 2
add: (x: Int)Int
scala> val a = add _
a: Int => Int = <function1>
scala> a(3)
res17: Int = 6
scala>

这样可以省去书写显示类型,否则将这样书写:

1
2
3
4
scala> val aa: Int => Int = add
aa: Int => Int = <function1>
scala>

符号“=>”用法

用法1:函数类型

输入类型 => 返回类型

1
2
3
4
scala> def func(f: Int => String): Unit = {}
func: (f: Int => String)Unit
scala>

用法2:Lambda表达式

1
2
3
4
scala> def tes(x: Int): Int => Unit = { _ => print("asd")}
tes: (x: Int)Int => Unit
scala>

用法3:模式匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
scala> def chen(x: Int): String = x match {
| case 1 => "One"
| case 2 => "Two"
| case _ => throw new IllegalArgumentException
| }
chen: (x: Int)String
scala> chen(1)
res6: String = One
scala> chen(3)
java.lang.IllegalArgumentException
at .chen(<console>:14)
... 32 elided
scala>

用法4:为倒入库提供别名

1
2
3
4
scala> import java.util.{List=>JList}
import java.util.{List=>JList}
scala>

用法5:传名参数

1
2
3
4
5
6
7
8
9
scala> def byname(in: => Int) = {}
byname: (in: => Int)Unit
scala> def f(in: Int) = in
f: (in: Int)Int
scala> byname(f(3))
scala>

用法6:自引用类型

http://hongjiang.info/scala-type-system-self-type/

小结

Scala里一些符号的组合用法广泛,写本篇方便快速查询。

参考

Scala可变长度参数与:_*使用

scala类型系统:9) this别名&自身类型