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