以下模式似乎是惯用的斯卡拉: class Foo() {}
object Foo { def apply() = new Foo() }
val x = Foo()
什么是惯用的做法的动机是什么?在哪些情况下我应该不是提供工厂方法,迫使客户使用val y = new Foo()?伴随对象的所有案例是否应提供工厂方法?
这里是代码和输出: //A scala class with a private variable and one method
class A {
private var a1 = "Zoom"
def A1(): Unit = {
println("A1 Class")
}
}
//A companion object
object A {
我对kotlin很新颖,我想知道是否有可能,以及如果违反了最佳实践,从伴随对象中访问伴随对象之外的方法和变量。 例如 class A {
fun doStuff(): Boolean = return true
companion object{
public fun stuffDone(): Boolean = return doStuff()
}