【问题标题】:Structural Type Parameters in Scala CollectionsScala 集合中的结构类型参数
【发布时间】:2013-03-13 17:01:23
【问题描述】:

免责声明: 这是可能的问题,而不是在实践中推荐的问题。

假设你有以下课程:

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 编译器为 ::: 选择正确的类型并生成指定结构类型的列表?

【问题讨论】:

  • 你有你的答案,但请注意,当使用结构类型时,调用方法(或访问属性,这是同一件事)的成本要高得多。
  • @RandallSchulz 谢谢,正如我在 免责声明 中所述,这不是实际使用的代码,只是对 Scala 的结构类型系统和推理的可能性进行的思想实验.我知道结合结构类型,尤其是隐式转换,可能会对性能产生严重影响。

标签: scala scala-collections structural-typing


【解决方案1】:
(points1 : List[{val x : Int; val y : Int}]) ::: points2 ::: points3

应该可以!

【讨论】:

  • 谢谢。发布几分钟后,我发现我的真正问题与我上面提出的问题无关。在实际示例中,point3 类与其他两个不完全匹配,并且依赖于隐式转换。我错过了触发隐式转换的提示,这导致::: 恢复为使用List[Product] 作为返回类型。谢谢!
【解决方案2】:

如果你想写如下代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多