[英]Generic parameters for a constructor in Scala
考虑以下设计的Java示例:
public class Example {
private final Object value;
private final List<?> aListOfTheseThings;
public <T> Example(final T t, final List<T> aListOfTheseThings) {
this.value = t;
this.aListOfTheseThings = aListOfTheseThings;
}
}
我在这个例子中关心的是:
Example
未参数化 t
参数化 (这是一个人为的例子,我并不关心(2)
但我确实关心那里有一个类型参数,这个类参数在类的定义中没有提到)。
现在在Scala中我尝试了以下方法:
class Example private[this](
private val value: AnyRef,
private val aListOfTheseThings: List[_]) {
def this[T](t: T, aListOfTheseThings: List[T]) {
this(t, aListOfTheseThings)
}
}
......但这是不可能的。 显然,类型参数在构造函数中无效(在this
)。
是否有机会将上述Java代码翻译成Scala?
也许这个帮助:
sealed trait Example
object Example {
def apply[T <: AnyRef](t:T, aListOfTheseThings: List[T]): Example =
new ExampleImpl(t, aListOfTheseThings)
private class ExampleImpl(
val value: AnyRef,
val aListOfTheseThings: List[_]) extends Example
}
这使得类的私有构造函数Example
。 不能通过Example
trait访问value和aListOfTheseThings
(除非你可以访问它)
Nyavro建议使用辅助apply
方法是一个很好的方法。 在某些情况下可能适用的另一种选择是子类化:
trait Example {
val value: Any
val things: List[_]
}
class SameTypeExample[T](val value: T, val things: List[T]) extends Example
子类化的优点是value
和things
存储相同类型的约束不会丢失,并且可以通过模式匹配重新发现:
def handle(example: Example) = example match {
case st: SameTypeExample[t] =>
st.value :: st.things
}
子类化是Scala中用于临时隐藏构造时存在的信息的一种通用技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.