(二)scala构造器和伴生对象

2017-12-26 10:34:17来源:oschina作者:appointint人点击

分享

构造器的使用


调用apply方法时.apply可以省略


object Hello{
def main(args:Array[String]){
//println("hello world")

val m1 = new Man("Zhangsan")

// 会报错
// m.apply("zhu")
val list = List("aa", "bb")
//调用的是伴生对象中的apply
val m2 = Man("Wangwu")
println("000000000000000000000");
//调用的是class中的apply
m2("liu", 33)
}
}
//如果没有显示定义构造方法,编译器会分配一个默认的(不带参数)主构造器
//主构造器跟在类名后面
class Man(var name:String){
//被主构造器调用
//println(name)
var id:Int = 0
var age:Int = 0//辅助构造器,第一行代码必须是对主构造器或者另外一个辅助构造器的调用
def this(name:String, id:Int){
this(name)
this.id = id
}def this(name:String, id:Int, age:Int){
this(name,id)
//this.id = id
this.age = age
}//def apply(name:String,id:Int): Unit = {
//println("Unit")
//}
//也可以返回list
//def apply(name: String,id:Int): List[String] = List("ds","werfew")
def apply(name:String,id:Int):Man= new Man(name,id)
}
object Man{
def apply(name:String): Man = {
new Man(name,id)
//println("object Man")
// def apply(name:String):Man = new Man(name)
}

apply方法的使用


object apply {
def main(args: Array[String]): Unit = {
val anyObject = new SomeClass
println(anyObject("key1"))val ss = SomeClass("aa")
println(ss)val email = EMail("fantasia", "sina.com")
println(email)
val email2 = new Email
email2("Test")
}
}
class SomeClass {
println("SomeClass ........");
def apply(key: String): String = {
println("SomeClass apply()" + key)
key
}
}
object SomeClass{
def apply(a:String){
println("SomClass object apply()" + a)
}
}
class Email{
def apply(x:String){
println("Email apply");
println(x);
}
}
object EMail {
def apply(user: String, domain: String): String = {
println("Email Object apply()")
user + "@" + domain
}
}

unapply的使用


object Apply_unapply {
def main(args: Array[String]): Unit = {
val currency = Currency(30.2, "EUR")
currency match {
case Currency(amount, "USD") => println("$" + amount)
case _ => println("No match.")
}
}
}class Currency(val value: Double, val unit: String) {
}
object Currency{
def apply(value: Double, unit: String): Currency = new Currency(value, unit)def unapply(currency: Currency): Option[(Double, String)] = {
if (currency == null){
None
}
else{
Some(currency.value, currency.unit)
}
}
}

微信扫一扫

第七城市微信公众平台