[英]Scala provide type information in subclassed generic function
Here is my problem. 这是我的问题。
I have an abstract class that defines a method with type parameters as input and output. 我有一个抽象类,定义了一个将类型参数作为输入和输出的方法。 I want the subclasses to provide the type information when subclassing but I want to do it in a way that I don't parametrize the whole class. 我希望子类在提供子类时提供类型信息,但我希望以不对整个类进行参数化的方式来实现。
Some pseudo code of what I'm aiming at. 我要针对的一些伪代码。
abstract class A {
def foo[T](t: T): T
}
class B() extends A {
override foo[Int](t: Int): Int = t + 1
}
class C() extends A {
override foo[Double](t: Double): Double = t + 1.0
}
How do I pass the type information on subclassing? 如何在子类上传递类型信息? I looked at similar problems. 我看着类似的问题。 They address that with self types, type classes and abstract types. 他们通过自我类型,类型类和抽象类型来解决这个问题。
Thanks 谢谢
As you've said, an abstract type on A
can solve that: 如您所说, A
的抽象类型可以解决以下问题:
abstract class A {
type T
def foo(t: T): T
}
class B extends A {
override type T = Int
override def foo(t: Int): Int = t + 1
}
class C extends A {
override type T = Double
override def foo(t: Double): Double = t + 1.0
}
What about "parameterizing" on the abstract Class: 关于抽象类的“参数化”呢?
abstract class A[T] {
def foo(t: T): T
}
class B extends A[Int] {
override def foo(t: Int): Int = t + 1
}
class C extends A[Double] {
override def foo(t: Double): Double = t + 1.0
}
Your A
is specifically promising that it can be called with any T
. 您的A
特别承诺可以与任何 T
一起调用。 So any type that extends it must fulfill that promise. 因此,任何扩展它的类型都必须兑现这一承诺。
val a: A = ...
val x = a.foo("a") // calls foo[String]
val y = a.foo(1) // calls foo[Int]
is perfectly good code. 是完美的代码。 But when it's executed, a
can actually be a B
, C
, or anything that extends A
. 但是执行时, a
实际上可以是B
, C
或任何扩展A
东西。 So "providing the type information when subclassing" doesn't really make sense: it would completely break the meaning of subtyping (or of type parameters). 因此,“在子类化时提供类型信息”实际上没有任何意义:它将完全破坏子类型化(或类型参数)的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.