Scala type alias - how to have a type that represents multiple data types

Is it possible to define a type alias that represents several data types?

package object scala {
  type SingleDimension = Double
  type MultiDimensionMap = Map[String, Double]
  type MultiDimensionList = List[Tuple2[String, Double]]
}

eg. I need a suptertype type that lets you say DataDimension, which represent only the above three types. so i can do the following:

trait AbstractDataWorker[T] {

  def formula(d: Double): T
}


class multiDimensionWorker extends AbstractDataWorker[MultiDimensionMap] {

  type T = MultiDimensionMap
  override def formula(d: Double): MultiDimensionMap = {

    Map[String, Double]()
  }

}

class singleDimensionWorker extends AbstractDataWorker[SingleDimension] {

  type T = SingleDimension
  override def formula(d: Double): SingleDimension = {
    2.0
  }

}

But the following should give a compilation error. He is currently working.

class stringDimensionWorker extends AbstractDataWorker[String] {

  type T = String
  override def formula(d: Double): String = {

    "hello"
  }

}
0
source share
1 answer

You can make them real classes extending one attribute instead of type aliases:

sealed trait DimensionLike
case class SingleDimension(value: Double) extends DimensionLike
case class MultiDimensionMap(value: Map[String, Double]) extends DimensionLike
case class MultiDinmensionList(value: List[(String, Double)]) extends DimensionLike

abstract class AbstractDataWorker[T <: DimensionLike] {
  def formula(d: Double): T
}

class MultiDimensionWorker extends AbstractDataWorker[MultiDimensionMap] {
  // ...
}

Or you can create a class with implicit implementations for these type aliases. Then do AbstractDataWorkeran abstract classand add a context binding for this type to the type argument:

type SingleDimension = Double
type MultiDimensionMap = Map[String, Double]
type MultiDimensionList = List[(String, Double)]

sealed trait IsDimensionLike[T]
object IsDimensionLike {
  implicit object singleDimension extends IsDimensionLike[SingleDimension]
  implicit object multiDimensionMap extends IsDimensionLike[MultiDimensionMap]
  implicit object multiDimensionList extends IsDimensionLike[MultiDimensionList]
}

abstract class AbstractDataWorker[T : IsDimensionLike] {
  def formula(d: Double): T
}

class MultiDimensionWorker extends AbstractDataWorker[MultiDimensionMap] {
  // ...
}
+5

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


All Articles