Daniil Iaitskov
Daniil Iaitskov

Reputation: 6069

How avoid type repetition for inherited fields in Scala

I start slow migration from Java to Scala and facing issues. One of them is clumsy constructor arguments. I know I cannot avoid them, but at least I would like to introduce some sort of type alias like C++ has typename to be used in subclasses.

case class A[E <: Throwable]
(
  mappers: Map[Class[_ :< Throwable], ExceptionMapper[_ <: Throwable]]
) {
}

case class B[CompletionException]
(
  mappers: Map[Class[_ :< Throwable], ExceptionMapper[_ <: Throwable]]
) extends A(mappers) {
}

So in sample above mappers field has horrible type and I would like to type it once in base class only.

Upvotes: 1

Views: 65

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51693

In Scala you can introduce type alias

type M = Map[Class[_ <: Throwable], ExceptionMapper[_ <: Throwable]]

class A[E <: Throwable]
(
  mappers: M
) {
}

class B[CompletionException]
(
  mappers: M
) extends A(mappers) {
}

By the way, case classes shouldn't extend each other because of issues with equals/hashCode.

Upvotes: 6

Related Questions