Scala type alias including companion object [novice]

I would like to write a type alias to shorten, hide and encapsulate Scala code. Suppose I have a collection that has the property of being a list of cards whose value is a tuple. My type will write something like List[Map[Int, (String, String)]] or something more general, as my application allows. I could imagine that the supertype asks for Seq[MapLike[Int, Any]] or something else floating on my boat, with specific subclasses, more specific.

I would like to write an alias for this long type.

 class ConcreteClass { type DataType = List[Map[Int, (String, String)]] ... } 

Then I would happily use ConcreteClass#DataType wherever I can take it and use it.

Now suppose I add a function

 def foo(a : DataType) { ... } 

And I want to call it from the outside with an empty list. I can call foo(List()) , but when I want to change my base type to another Seq type, I will have to go back and change this code. Also, it is not very explicit; this empty list is intended as a DataType . And the companion object has no associated List methods, so I cannot call DataType() or DataType.empty . This will be even more annoying when I need non-empty lists, since I will have to write out a significant portion of this long type.

Can I ask Scala in some way to understand my type as the same thing, including a companion object with its creator methods, in the interest of shortening the code and its black processing? Or, for some reason, why shouldn't I do this in the first place?

+7
scala encapsulation companion-object type-alias
source share
2 answers

The answer was pretty simple:

 class ConcreteClass { type DataType = List[String] } object ConcreteClass { val DataType = List } val d = ConcreteClass.DataType.empty 

This allows my code to call ConcreteClass.DataType to create lists with all the methods from the list and little effort.

Many thanks to Oleg for your understanding. His answer is also better if you do not want to delegate a list of any call to ConcreteClass.DataType, but precisely control what you want to allow callers.

+7
source share

How about this?

 class ConcreteClass { type DataType = List[String] } object DataType { def apply(): ConcreteClass#DataType = Nil } //... val a = DataType() 
+5
source share

All Articles