Scala将类型参数传递给对象

Sha*_*ian 10 scala object type-parameter

在Scala v 2.7.7中

我有一个文件

class Something[T] extends Other

object Something extends OtherConstructor[Something]
Run Code Online (Sandbox Code Playgroud)

这会引发错误:

class Something
take type parameters object Something extends OtherConstructor [Something] {

但是,我不能这样做

object Something[T] extends OtherConstructor[Something[T]]
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误:

错误:';' 预期,但'''发现.

是否可以将类型参数发送到对象?或者我应该改变并简单地使用Otherconstructor

Sco*_*ith 5

object Foo[T]您可以通过将类型参数移至以下方法来解决需要的一般问题object Foo

class Foo[T](t1: T, t2: T)

object Foo {
  def apply[T](x: T): Foo[T] = new Foo(x, x)
  def apply[T](x: T, y: T): Foo[T] = new Foo(x, y)
}
Run Code Online (Sandbox Code Playgroud)

如果您确实需要每个 T 一个对象,您可以创建一个类,并让无类型同伴从 apply 返回它。

class Foo[T](t1: T, t2: T)

class FooCompanion[T] {
  def apply(x: T): Foo[T] = new Foo(x, x)
  def apply(x: T, y: T): Foo[T] = new Foo(x, y)
}

object Foo {
  def apply[T] = new FooCompanion[T]
}

object demo extends App {
  val x: Foo[Double] = Foo.apply.apply(1.23)  // this is what is really happening
  val y: Foo[Int] = Foo[Int](123)             // with the type both apply calls are automatic
}
Run Code Online (Sandbox Code Playgroud)

请注意,这将在每次调用时重新构造 Foo[T] 同伴,因此您希望保持它的轻量级和无状态性。

上述问题的显式解决方案:

class Other

class OtherConstructor[O <: Other] {
  def apply(o: O): O = o  // constructor 1 in base class
}

class Something[T](value: T) extends Other

class SomethingConstructor[T] extends OtherConstructor[Something[T]] {
  def apply(o: T, s: String) = new Something[T](o)   // constructor 2 in subclass
}

object Something {
  def apply[T] = new SomethingConstructor[T] // the "constructor constructor" method
}

object demoX extends App {
  val si = new Something(123)
  val sd = new Something(1.23)

  val si1: Something[Int] = Something[Int](si)                    // OtherConstructor.apply
  val sd1: Something[Double] = Something[Double](1.23, "hello")   // SomethingConstructor[Double].apply
}
Run Code Online (Sandbox Code Playgroud)


Tho*_*ung 3

一个对象必须有一个具体的类型。Scala 对象结构也不例外。

一个有效的定义是

object Something extends OtherConstructor[Something[T]] { }
Run Code Online (Sandbox Code Playgroud)

哪里T有一些具体的类型