chrsan
chrsan

Reputation: 3400

Scala types question

I'm in a situation where I want to create an immutable like collection and one mutable. They both share some parts which doesn't differ regarding to immutability or not.

Maybe I should dive in and have a look at how the Scala collections are implemented, but I'm not trying to create a full blown collection type.

I have this right now, but it doesn't feel quite right.

trait StyleMapping[T <: Style[T]] {
  type Mappings <: scala.collection.Map[Option[String], T]
  val mappings: Mappings

  def get(classNames: List[String]): Option[T] = {
    mappings.get(...) // Do something here.
  }
}

and this is an example of an immutable implementation:

class ImmutableStyleMapping[T <: Style[T]](
    val mappings: Map[Option[String], T)
  extends StyleMapping[T] {
  type Mappings = Map[Option[String], T]
}

This works, but it feels like I'm repeating the types all over the code. Is an abstract type the best way to go, or should I design this differently? Would be grateful for some insight of how this might be done differently.

Upvotes: 1

Views: 174

Answers (1)

huynhjl
huynhjl

Reputation: 41646

Given what you showed here, I don't think you need to use an abstract type. Your StyleMapping trait implementation would have to work with a generic Map. Only the subclasses would care about whether the map was immutable or mutable. With that in mind, it can be simplified as:

trait StyleMapping[T <: Style[T]] {
  val mappings: collection.Map[Option[String], T]
  def get(classNames: List[String]): Option[T] = {
    mappings.get(...) // Do something here.
  }
}

class ImmutableStyleMapping[T <: Style[T]](
  val mappings: Map[Option[String],T]) extends StyleMapping[T]

class MutableStyleMapping[T <: Style[T]](
  val mappings: collection.mutable.Map[Option[String],T]) extends StyleMapping[T]

In each case mappings will have the immutable or mutable property desired and this will be enforced by the compiler.

Upvotes: 1

Related Questions