object People { private var mouthNum = 1 println("this People object!") def getMouthNum = mouthNum } People.getMouthNum
执行程序以后能够看到,构造方法只被调用了一次。编程
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
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")
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")
scalac
编译源文件而后再使用 scala
执行def main(args: Array[String])
,并且必须定义在 object 中object Test { def main(args: Array[String]) { println("I'm learning the Scala!!!") } }
object Test extends App { if (args.length > 0) println("hello, " + args(0)) else println("Hello World!!!") }
object Color extends Enumeration { val RED, BLUE, YELLOW, WHITE, BLACK = Value } Color.RED
.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