0

Many methods of a program receive as parameter a List[Map[String, String]].

I'd like to formalize it and make it more readable by defining a class such as:

class MyClass extends  List[Map[String, String]]

However it throws an error:

Illegal inheritance from sealed class 'List'

Is there a proper way to handle it?

user51
  • 8,843
  • 21
  • 79
  • 158
Rolintocour
  • 2,934
  • 4
  • 32
  • 63

2 Answers2

5

The thing you need is called a type alias:

type MyClass = List[Map[String, String]]

https://alvinalexander.com/scala/scala-type-aliases-syntax-examples

You get the error because you're trying to extend a sealed trait which can be only extended in the same file in which the trait is defined.

https://alvinalexander.com/scala/scala-type-aliases-syntax-examples https://underscore.io/blog/posts/2015/06/02/everything-about-sealed.html

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32
1

One option is to use composition rather than inheritance:

case class MyClass(value: List[Map[String, String]])

This is more type-safe than using a type alias, as you can only pass an instance of MyClass where MyClass is expected, whereas the type alias approach allows any List[Map[String, String]]. It can also help avoid primitive obsession. Which one you choose depends on your use case.

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45