专注于快乐的事情

Scala类的学习

本文于1197天之前发表,文中内容可能已经过时。

类的学习

单例对象

 object Timer {
  var count = 0
  def currentCount(): Long = {
    count += 1
    count
  }
}

执行结果

scala> Timer.currentCount()
res0: Long = 1

伴生对象

单例对象可以和类具有相同的名称,此时该对象也被称为“伴生对象”。通常将伴生对象作为工厂使用

class Bar(foo: String)

object Bar {
  def apply(foo: String) = new Bar(foo)
}

使用伴生对象的apply方法是Scala中构建对象的常用手法。例如,Array(1, 4, 9,16)返回一个数组,用的就是Array伴生对象的apply方法

apply是什么?

当类或对象有一个主要用途的时候,可以使用apply

object FooMaker {
  def apply() = println("hello world")

  def main(arg: Array[String]) {
    val newFoo = FooMaker();
  }
}

#Trait

概念上类似Java的interface, 但是更强大

trait Philosophical {
def philosophize() {
println(“I consume memory, therefore I am!”)
}
}
mix in有两种方式, extend和with

extend

class Frog extends Philosophical { //mix in Philosophical trait
    override def toString = "green"
}

with

with, 需要显式的指明超类

class Animal
trait HasLegs
class Frog extends Animal with Philosophical with HasLegs {
    override def toString = "green"
}

Trait真正的作用在于, 模块封装, 可以把相对独立的功能封装在trait中, 并在需要的时候进行mix in,

其他

参考网站

评论系统未开启,无法评论!