2013-03-13 72 views
1

免责声明:这是什么可能一个问题,不是会在实践中推荐。结构类型参数

比方说,你给出的以下类:

case class point1(x: Int, y:Int) 
case class point2(x: Int, y:Int) 
case class point3(x: Int, y:Int) 

,你有一个包含每个类

val points1 = List[point1](/*Can be empty for this example*/) 
val points2 = List[point2]() 
val points3 = List[point3]() 

的一些号码表是有可能创造一个结构类型的列表可以使用常用技术如++,:::.union(..)来包含所有的三种点类型,而不需要定义所有类的共同特征,即

var points: List[{def x: Int; def y: Int}] = 
    points1 ::: points2 ::: points3 

据我所知,如上所述,:::运营商返回List[Product]。我想这是提供正确的提示,Scala编译器的问题,因为下面的代码不会产生正确类型的列表:

var points: ListBuffer[{def x: Int; def y: Int}] = List[{def x: Int; def y: Int}]() 
points1.foreach(e => { 
    val p: {def x: Int; def y: Int} = e; 
    points.append(p); 
}) 
points2.foreach(e => { 
    val p: {def x: Int; def y: Int} = e; 
    points.append(p); 
}) 

是否有任何提示我可以给你的帮助Scala编译器来选择正确的类型为:::并产生指定结构类型的列表?

+0

你有你的答案,但是要知道,调用一个方法(或访问性房地产的成本,这是同样的事情)在使用结构类型时显着更高。 – 2013-03-13 17:47:24

+0

@RandallSchulz谢谢,正如我在**免责声明**中所述,这不是代码在实践中被使用,只是一个关于Scala的结构类型系统和推理的可能性的思考实验。我明白,结合结构分类,尤其是隐式转换,会对性能造成严重影响。 – Syllepsis 2013-03-14 13:07:56

回答

2
(points1 : List[{val x : Int; val y : Int}]) ::: points2 ::: points3 

应该工作!

+0

谢谢。发布几分钟后,我发现我真正的问题,这与我上面提到的问题并无关系。在实际的例子中,'point3'类不完全匹配其他两个,并且依赖于隐式转换。我错过了触发隐式转换的提示,导致':::'返回使用'List [Product]'作为返回类型。谢谢! – Syllepsis 2013-03-13 17:34:59

0

如果要编写以下代码:

var points: List[{def x: Int; def y: Int}] = 
points1 ::: points2 ::: points3 

它的工作原理:

implicit def typer[B >: A, A <: { def x: Int; def y: Int }](t: List[B]): List[A] = t 

var points: List[{def x: Int; def y: Int}] = 
points1 ::: points2 ::: points3