Good programmers to share large data line learning scala single and associated objects
Singleton scala
object SingletonDemo {
def main(args: Array[String]): Unit = {
val s = SessionFactory
println(s.getSession)
println (s.getSession.size) //.size several session object obtained
}
}
object SessionFactory{
println ( "SessionFactory been executed")
//counter
where i = 5
// array of objects stored session
val sessions = new ArrayBuffer[Session]()
while(i>1){
println ( "while being executed")
sessions.append(new Session)
i -= 1
}
// Get the session object
def getSession = sessions
}
class Session{
}
Associated Objects
Singleton object includes a companion object between the objects associated with the class can access each other, even if the private modifier private fields and attributes
First, the object is associated a singleton object, singleton object defined by the object
In the scala, are two singletons
1. association not automatically associated with a particular class singleton object, called independent object -> Standalone Object
2. singleton object associated with a class, the singleton object class is a class the same name, referred to as associated objects -> Companion Object
class companionObject {
was id = 0
private val name = "zhaoxiaodan"
def printContent() = {
println(name+companionObject.Constant)
}
}
object companionObject {
private val Constant = " is my goddess"
def main(args: Array[String]): Unit = {
val co = new companionObject
co.id = 8
println(co.id)
println(co.name)
co.printContent() //zhaoxiaodan is my goddess
}
}
and apply unapply (typically apply method defined in companion object class)
apply method commonly referred implantation method, to make the initialization operation in a companion object class
The method does not need to apply the parameter list and the master list unified structure
The method generally unapply extraction method, the extraction method may unapply using a fixed number of objects and values constructor
unapply method returns an Option, if there Option value, then there will be a some internal objects to encapsulate these values
class ApplyDemo(val name: String, val age: Int, val faceValue: Int) {
}
object ApplyDemo {
// injection method
def apply(name: String, age: Int): ApplyDemo = {
new ApplyDemo (name, age, faceValue = 80) // Initialization
}
//method of extraction
def unapply(applyDemo: ApplyDemo):Option[(String,Int,Int)]={
if (applyDemo == null){
None
}else{
Some(applyDemo.name,applyDemo.age,applyDemo.faceValue)
}
}
}
object ApplyTest{
def main(args: Array[String]): Unit = {
val applyDemo = ApplyDemo ( "resection. OF", 18)
applyDemo match {
case ApplyDemo ( "resection. OF", age, faceValue) => println (s "name: resection. OF, age: $ age, fv: $ faceValue")
case _=> println("is null")
}
}
}