Using overloaded, typed methods in a collection

I am new to Scala and struggling with the following:

I have database objects (type BaseDoc) and value objects (type BaseVO). Now there are several conversion methods (all called "convert") that take an instance of an object and accordingly convert it to another type: for example:

def convert(doc: ClickDoc): ClickVO = ...
def convert(doc: PointDoc): PointVO = ...
def convert(doc: WindowDoc): WindowVO = ...

Now I sometimes need to convert a list of objects. How would I do this - I tried:

def convert[D <: BaseDoc, V <: BaseVO](docs: List[D]):List[V] = docs match {
    case List() => List()
    case xs => xs.map(doc => convert(doc))
}

The result is "the overloaded value of the method value with alternatives ...". I tried to add manifest information to it, but could not get it to work.

I could not even create one method for each, because it would say that they have the same type of parameter after deleting the type (List).

Ideas are welcome!

+3
2

, . List Scala. - map . - :

def convert(docs: List[BaseDoc]):List[BaseVO] = docs map {
    case doc: ClickDoc => convert(doc)
    case doc: PointDoc => convert(doc)
    case doc: WindowDoc => convert(doc)
}

- convert BaseDoc .

+4

:

  //case class MyBaseDoc(x: Int, y: Int)
  //case class BaseVO(x: Int, y: Int)
  //case class ClickDoc(x: Int, y: Int) extends MyBaseDoc(x, y)
  //case class ClickVO(var x: Int, var y: Int) extends BaseVO(x, y)

  def convert(doc: ClickDoc): ClickVO  = doc match {
    case null => null
    case _ =>
      val result = new ClickVO
      result.x = doc.x
      result.y = doc.y
      result
  }


  def convert(docs: List[MyBaseDoc]):List[BaseVO] = docs match {
    case List() => List()
    case xs => xs.map(doc => convert(doc.asInstanceOf[ClickDoc]))
  }
+1

Source: https://habr.com/ru/post/1748326/


All Articles