Scala 学习(6)之「对象」

object

  • 至关于 class 的单个实例,一般在里面放一些静态的 field 或者 method,第一次调用 object 的方法时,就会执行 object 的 constructor,也就是 object 内部不在 method 中的代码,须要注意的是,object 不能定义接受参数的 constructor
  • object 的 constructor 只会在其第一次被调用时执行一次,之后再调用就不会再次执行了
  • object 一般用于单例模式的实现,或者放 class 的静态成员,好比工具方法 object,一般在里面放一些静态的 field 或者 method
object People {
	private var mouthNum = 1
	println("this People object!")
	def getMouthNum = mouthNum
}
People.getMouthNum

执行程序以后能够看到,构造方法只被调用了一次。编程

伴生对象

  • 若是一个程序中,若是有一个 class,还有一个与 class 同名的 object,那么就称这个 object 是 class 的伴生对象, class 是 object 的伴生类
  • 伴生类和伴生对象必须存放在一个 .scala 文件之中
  • 伴生类和伴生对象,最大的特色就在于,它们互相能够访问彼此的 private field
object People {
	private val mouthNum = 1
	def getMouthNum = mouthNum
}

class People(val name: String, val age: Int) {
	def sayHello = println("Hi, " + name + ", I guess you are " + age + " years old!" + ", and you have " + People.mouthNum + " mounth.")
}

val people = new People("0mifang", 18)

// Hi, 0mifang, I guess you are 18 years old!, and you have 1 mounth.
people.sayHello

继承抽象类

  • object 的功能其实和 class 相似,除了不能定义接受参数的 constructor 以外,object 也能够继承抽象类,并覆盖抽象类中的方法
abstract class Eat(var message: String) {
	def eat(food: String): Unit
}

object EatImpl extends Eat("0mifang") {
	override def eat(food: String) = {
		println(message + " eat an " + name)
	}
}

EatImpl.sayHello("ice cream")

apply方法

  • 一般在伴生对象中实现 apply 方法,并在其中实现构造伴生类的对象的功能,而建立伴生类的对象时,一般不会使用 new Class 的方式,而是使用 Class() 的方式,隐式地调用伴生对象得 apply 方法,这样会让对象建立更加简洁
class Person(val name: String)	//建立伴生类
object Person {	//建立伴生对象
	def apply(name: String) = new Person(name)
}

val p1 = new Person("0mifang1")
val p2 = Person("0mifang2")

main方法

  • 须要使用命令行敲入 scalac 编译源文件而后再使用 scala 执行
  • Scala 中的 main 方法定义为 def main(args: Array[String]) ,并且必须定义在 object 中
object Test {
	def main(args: Array[String]) {
		println("I'm learning the Scala!!!")
	}
}
  • 除了本身实现 main 方法以外,还能够继承 App Trait,而后将须要在 main 方法中运行的代码,直接做为 object 的 constructor 代码;并且用 args 能够接受传入的参数
  • App Trait 的工做原理为:App Trait 继承自 DelayedInit Trait,scalac 命令进行编译时,会把继承 App Trait 的 object 的 constructor 代码都放到 DelayedInit Trait 的 delayedInit 方法中执行
object Test extends App {
	if (args.length > 0) println("hello, " + args(0))
	else println("Hello World!!!")
}

用 object 来实现枚举功能

  • 须要用 object 继承 Enumeration 类,而且调用 Value 方法来初始化枚举值
object Color extends Enumeration {
	val RED, BLUE, YELLOW, WHITE, BLACK = Value
}
Color.RED
  • 还能够经过 Value 传入枚举值的 id 和 name,经过 .id.toString 能够获取; 还能够经过 id 和 name 来查找枚举值
object Color extends Enumeration {
	val RED = Value(0, "red")
	val BLUE = Value(1, "blue")
	val YELLOW = Value(2, "yellow")
	val WHITE = Value(3, "white")
	val BLACK = Value(4, "black")
}
Color(0)
Color.withName("red")
  • 使用枚举 object.values 能够遍历枚举值
for (ele <- Color.values) println(ele)

欢迎关注,本号将持续分享本人在编程路上的各类见闻。app

相关文章
相关标签/搜索