首页 文章

Scala集合中的结构类型参数

提问于
浏览
1

Disclaimer: 这是一个什么是 possible 的问题,而不是在实践中推荐的问题 .

假设您有以下课程:

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

2 回答

  • 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
    
  • 0
    (points1 : List[{val x : Int; val y : Int}]) ::: points2 ::: points3
    

    应该管用!

相关问题