两个不同的类如何扩展同一个类在Scala中返回相同的类型

时间:2017-12-12 07:08:58

标签: scala type-mismatch

我希望能够做到这样的事情:

假设我们有两个Scala包AB。在B中,我有两个类,如下所示:

class Structure{
    case class StructureA(x:String, y:String)
    case class StructureB(x:Int, y:Int)
}
class OperationB extend Structure{
    def optB(someData:String): Array[(StructureA,StructureB)] = {...}
}

A中,我有一个这样的课程:

import B.Structure
class OperationA extend Structure {
    def optA(data:Array[(StructureA,StructureB)]): Array[(StructureA,StructureB)] = {...}
}

以下是我的项目条目:

import B.{Structure,OperationB }
import A.OperationA
object Main {
    def main(args: Array[String]): Unit = { 


        val BInstance = new OperationB()
        val BResult = BInstance.optB(someData)

        val AInstance = new OperationA()
        val AResult = AInstance.optA(BResult)

    }
}

问题是:

BResult是typeof Array [(StructureA,StructureB)]但是无法编译,错误信息是

type mismatch, expected Array[(A.StructureA,A.StructureB)] actual Array[(B.StructureA,B.StructureB)]

实际上我在其中添加了此代码,并且可以成功编译,但我认为这不是最佳解决方案。

   import B.{Structure,OperationB }
   import A.OperationA
   object Main {
    def main(args: Array[String]): Unit = { 


        val BInstance = new OperationB()
        val AInstance = new OperationA()

        // here convert it into proper type.
        val BResult = BInstance.optB(someData).map{
            case (a,b) => (a.asInstanceOf[AInstance.StructureA],b.asInstanceOf[AInstance.StructureB])
        }


        val AResult = AInstance.optA(BResult)

    }
}

很长一段时间以来一直困扰着我,任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您的代码会使Structure的每个实例都拥有自己的StructureAStructureB类型。由于他们不访问Structure,因此没有必要这样做。尝试扩展Structure以节省导入只是一个坏主意。

相反

package structure // or could be B.structure, or directly B
case class StructureA(x:String, y:String)
case class StructureB(x:Int, y:Int)

// in A
package A
import structure._
class OperationA {
    def optA(data:Array[(StructureA,StructureB)]): Array[(StructureA,StructureB)] = {...}
}

// in B
package B
import structure._
class OperationB {
    def optB(someData:String): Array[(StructureA,StructureB)] = {...}
}

另一种选择是

object Structure {
    case class StructureA(x:String, y:String)
    case class StructureB(x:Int, y:Int)
}