TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
23.scala编程思想笔记——类参数
欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/50445759
源码下载连接请见第一篇笔记。
在创建新对象时,一般是通过传递某些信息进行初始化,此时可以使用类参数。类参数列表看起来与方法参数列表一样,但是位于类名的后面:
例如:
import com.atomicscala.AtomicTest._
class ClassArg(a:Int) {
println(f)
def f():Int ={ a * 10 }
}
val ca = new ClassArg(19)
ca.f() is 190
其中变量a 在外部是不可见的。
看一个比较奇怪的例子如下:
import com.atomicscala.AtomicTest._
class ClassArg2(var a:Int)
class ClassArg3(val a:Int)
val ca2 = new ClassArg2(20)
val ca3 = new ClassArg3(21)
ca2.a is 20
ca3.a is 21
ca2.a = 24
ca2.a is 24
这些类定义没有显示的类体,它们的类体是隐式的,也能直接实例化的。
此外类可以有许多参数,如下:
import com.atomicscala.AtomicTest._
class Sum3(a1:Int, a2:Int, a3:Int) {
defresult():Int = { a1 + a2 + a3 }
}
new Sum3(13, 27, 44).result() is 84
可以使用可变元参数列表来支持任意数量的参数,如下:
import com.atomicscala.AtomicTest._
class Sum(args:Int*) {
defresult():Int = {
var total =0
for(n <-args) {
total +=n
}
total
}
}
new Sum(13, 27, 44).result() is 84
new Sum(1, 3, 5, 7, 9, 11).result() is 36
其中args末尾的* 将参数转换为一个序列,该序列可以在 for 表达式中使用使用<- 来遍历。
|
|