Scala辅助构造函数

时间:2011-12-09 04:24:51

标签: scala

以下是带有构造函数的Scala类。我的问题标有****

class Constructors( a:Int, b:Int ) {

def this() = 
{
  this(4,5)
  val s : String = "I want to dance after calling constructor"
  //**** Constructors does not take parameters error? What is this compile error?
  this(4,5)

}

def this(a:Int, b:Int, c:Int) =
{ 
  //called constructor's definition must precede calling constructor's definition
  this(5)
}

def this(d:Int) 
// **** no equal to works? def this(d:Int) = 
//that means you can have a constructor procedure and not a function
{
  this()

}

//A private constructor
private def this(a:String) = this(1)

//**** What does this mean?
private[this] def this(a:Boolean) = this("true")

//Constructors does not return anything, not even Unit (read void)
def this(a:Double):Unit = this(10,20,30)

}

您能否在上面的****中回答我的问题?例如,构造函数不带参数错误?什么是编译错误?

2 个答案:

答案 0 :(得分:13)

答案1:

scala> class Boo(a: Int) {
     |   def this() = { this(3); println("lol"); this(3) }
     |   def apply(n: Int) = { println("apply with " + n) }
     | }
defined class Boo

scala> new Boo()
lol
apply with 3
res0: Boo = Boo@fdd15b

第一个this(3)是主要构造函数的委派。第二个this(3)调用此对象的apply方法,即扩展为this.apply(3)。请注意上面的例子。

答案2:

=在构造函数定义中是可选的,因为它们实际上不返回任何内容。它们与常规方法有不同的语义。

答案3:

private[this]称为对象私有访问修饰符。对象无法访问其他对象的private[this]字段,即使它们都属于同一个类。因此它比private更严格。请注意以下错误:

scala> class Boo(private val a: Int, private[this] val b: Int) {
     |   def foo() {
     |     println((this.a, this.b))
     |   }
     | }
defined class Boo

scala> new Boo(2, 3).foo()
(2,3)

scala> class Boo(private val a: Int, private[this] val b: Int) {
     |   def foo(that: Boo) {
     |     println((this.a, this.b))
     |     println((that.a, that.b))
     |   }
     | }
<console>:17: error: value b is not a member of Boo
           println((that.a, that.b))
                                 ^

答案4:

与Ans 2相同。

答案 1 :(得分:0)

与问题2有关的是:

Scala Auxilliary Constructor behavior

这会导致错误,int b和int c缺少(默认)参数会引发称为构造函数的定义必须先于调用构造函数的定义