【发布时间】:2013-08-21 00:47:07
【问题描述】:
我来自 C++,并试图围绕 scala 的类型系统进行思考。
考虑以下 C++ 模板类:
template<class T>
class Point2
{
Point2( T x, T y ) :
x(x),
y(y)
{}
T x;
T y;
Point2<T> operator+( Point<T> const& other ) const
{
return Point<T>(x+other.x, y+other.y);
}
T sumComponents() const { return x+y; }
}
Point2<Double> p0(12.3, 45.6)
Point2<Double> p1(12.3, 45.6)
Point2<Double> p = p1+p2
Double d = p1.sumComponents()
我发现我想写这样的东西:
case class Point2[ T ] (x:T, y:T) {
def +() Point2[T]: = x+y
def sumComponents() T: = x+y
}
或者,(因为编译有问题),
trait Addable[T] { // Require T supports the + operatory
def +( that:T ):T
}
case class Point2[ T<:Addable[T] ] (x:T, y:T) {
def +() Point2[T]: = x+y
def sumComponents() T: = x+y
}
这同样有问题,因为我不能要求 Double 来扩展 Addable。
一般来说,我发现 scala 的类型系统适用于一组我不太了解的约束。
在 scala 中实现上述内容的惯用方式是什么?
C++ 模板程序员理解 scala 中泛型限制的正确方法是什么? (为什么我不能在 scala 中这样做?例如,是因为泛型是在实例化之前编译的吗?)
【问题讨论】:
-
虽然 Scala 作为一种大型且兼收并蓄的语言,可能会提供类似于 C++ 模板的东西,但针对您的问题公认的主流解决方案是“类型类”。正如他们所说,在罗马的时候,就像罗马人一样。
标签: c++ scala templates generics