(1)迭代器:迭代器(Iterator)不是一个集合,但是,提供了访问集合的一种方法。它包含两个函数:hasNext与next;hasNext可以判断迭代器是否还有下一个元素,next可以返回迭代器的下一个元素。
while循环
for循环
(2)class定义类,def定义方法
方法定义格式:def 方法名(参数名:参数类型): 返回值类型 = {函数体}
主构造器与辅助构造器:
主构造器是定义类时,类名后面标识参数类型与名称:
1 class Counter(val name: String, val mode: Int) { 2 private var value = 0 //value用来存储计数器的起始值 3 def increment(step: Int): Unit = { value += step} 4 def current(): Int = {value} 5 def info(): Unit = {printf("Name:%s and mode is %d\n",name,mode)} 6 } 7 object MyCounter{ 8 def main(args:Array[String]){ 9 val myCounter = new Counter("Timer",2) 10 myCounter.info //显示计数器信息 11 myCounter.increment(1) //设置步长 12 printf("Current Value is: %d\n",myCounter.current) //显示计数器当前值 13 } 14 }
辅助构造器是想java一样,在类内部实现,但是名称不是使用类名,而是this:
1 class Counter { 2 private var value = 0 //value用来存储计数器的起始值 3 private var name = "" //表示计数器的名称 4 private var mode = 1 //mode用来表示计数器类型(比如,1表示步数计数器,2表示时间计数器) 5 def this(name: String){ //第一个辅助构造器 6 this() //调用主构造器 7 this.name = name 8 } 9 def this (name: String, mode: Int){ //第二个辅助构造器 10 this(name) //调用前一个辅助构造器 11 this.mode = mode 12 } 13 def increment(step: Int): Unit = { value += step} 14 def current(): Int = {value} 15 def info(): Unit = {printf("Name:%s and mode is %d\n",name,mode)} 16 } 17 object MyCounter{ 18 def main(args:Array[String]){ 19 val myCounter1 = new Counter //主构造器 20 val myCounter2 = new Counter("Runner") //第一个辅助构造器,计数器的名称设置为Runner,用来计算跑步步数 21 val myCounter3 = new Counter("Timer",2) //第二个辅助构造器,计数器的名称设置为Timer,用来计算秒数 22 myCounter1.info //显示计数器信息 23 myCounter1.increment(1) //设置步长 24 printf("Current Value is: %d\n",myCounter1.current) //显示计数器当前值 25 myCounter2.info //显示计数器信息 26 myCounter2.increment(2) //设置步长 27 printf("Current Value is: %d\n",myCounter2.current) //显示计数器当前值 28 myCounter3.info //显示计数器信息 29 myCounter3.increment(3) //设置步长 30 printf("Current Value is: %d\n",myCounter3.current) //显示计数器当前值 31 32 } 33 }
getter与setter的使用方法
其实scala中也是险恶getter与setter方法的功能,但是没有定义为getter与setter:
1 class Counter { 2 private var privateValue = 0 //变成私有字段,并且修改字段名称 3 def value = privateValue //定义一个方法,方法的名称就是原来我们想要的字段的名称 4 def value_=(newValue: Int){ 5 if (newValue > 0) privateValue = newValue //只有提供的新值是正数,才允许修改 6 } 7 def increment(step: Int): Unit = { value += step} 8 def current(): Int = {value} 9 }
原文:https://www.cnblogs.com/liyuchao/p/12258870.html