Scala中apply方法以及函数返回有无unit的区别

来源:互联网 发布:mac桌面文件路径 编辑:程序博客网 时间:2024/06/06 08:42

scala中有个很独特的方法:apply,伴生类和伴生对象可以互相访问,没有权限限制

class ApplyTest{ //伴生类
def apply():Unit={
println(“I am into Scala so much!”)
}

def Try(n:Int):Int={ //返回值为int,最后一行的值为返回值
if(n<=0)
1
else
n*Try(n-1)
}
}

object ApplyTest{ //伴生对象
def apply()={ //这里不能用unit,函数有返回值的
println(“I am also in “)
new ApplyTest //伴生对象生产对象,而不是类
}
}

object helloScala{
def main(args: Array[String]): Unit ={ //unit表示main函数不需要返回值
val a = ApplyTest() //伴生对象生产一个类
val b = a.Try(5)
println(b)
a() //类中的apply函数
}
}

原创粉丝点击