Scala构造函数签名

Scala构造函数签名,scala,constructor,abstract-class,abstract,Scala,Constructor,Abstract Class,Abstract,可以在Scala中定义构造函数签名吗 abstract class A { def this (s: String): this.type // doesn't work def this (i: Int): this.type // doesn't work def this (d: Double): this.type // doesn't work } class B(var s: String) extends A { def this(i: In

可以在Scala中定义构造函数签名吗

abstract class A {
    def this (s: String): this.type // doesn't work
    def this (i: Int): this.type    // doesn't work
    def this (d: Double): this.type // doesn't work
}

class B(var s: String) extends A {
    def this(i: Int) = {
        this("int "+i.toString())
    }
    def this(d: Double) = {
        this("double "+d.toString())
    }
}

你想达到什么目标?您可以这样做:

abstract class A(i: Int)

case class B(s: String) extends A(s.toInt) {
  def this(i: Int) = {
    this(i.toString)
  }

  def this(d: Double) = {
    this(d.toString)
  }
}
用法:

B("1")
new B(1)
new B(1.0)

你想达到什么目标?您可以这样做:

abstract class A(i: Int)

case class B(s: String) extends A(s.toInt) {
  def this(i: Int) = {
    this(i.toString)
  }

  def this(d: Double) = {
    this(d.toString)
  }
}
用法:

B("1")
new B(1)
new B(1.0)

不,那是不可能的。构造函数是特殊的:您需要编写新的X而不是X,并且没有多态调度,例如,您不能执行def test[A]=new A。因此,在任何情况下,抽象构造函数都没有任何意义。

不,这是不可能的。构造函数是特殊的:您需要编写新的X而不是X,并且不存在多态调度,例如,您不能执行def test[A]=new A。因此,在任何情况下,抽象构造函数都没有任何意义。

正如其他答案所指出的,您不能完全按照自己的意愿执行,但有一种方法是使用工厂:

trait Foo { 
  // methods you need
}

trait FooCompanion[T <: Foo] {
  // these methods replace constructors in your example
  def apply(s: String): T
  def apply(i: Int): T
  ...
}

你可以有一些方法来解决这个问题。例如,在Scala collections库中使用此模式。

正如其他答案所指出的那样,您不能完全按照自己的意愿进行操作,但一种方法是使用工厂:

trait Foo { 
  // methods you need
}

trait FooCompanion[T <: Foo] {
  // these methods replace constructors in your example
  def apply(s: String): T
  def apply(i: Int): T
  ...
}

你可以有一些方法来解决这个问题。例如,在Scala collections库中使用此模式。

抽象类用作接口。如果您试图确保类具有单参数Int构造函数,则不可能将抽象类用作接口是毫无意义的。Scala中的trait和Java中的接口与这两种语言中的抽象类有着非常不同的使用限制?如果需要的话,我可以写一个更详细的例子来说明我试图实现的目标。Traits可能根本没有构造函数参数。这不能与他们没有构造函数混淆,因为他们有,只是那些构造函数不能接受参数。抽象类被用作接口。如果你试图保证你的类有一个单参数Int构造函数,那么将抽象类用作接口是不可能的。Scala中的trait和Java中的接口与这两种语言中的抽象类有着非常不同的使用限制?如果需要的话,我可以写一个更详细的例子来说明我试图实现的目标。Traits可能根本没有构造函数参数。这并不是说它们没有构造函数,因为它们有,只是那些构造函数不能接受任何参数。