What I'm trying to do is create a case class that I can use when matching patterns that has exactly one field, for example. immutable set. In addition, I would like to use functions such as map, foldLeft, etc., which should be passed to the set. I tried this, as in the following:
case class foo(s:Set[String]) extends Iterable[String] { override def iterator = s.iterator }
Now, if I try to use, for example, the display function, I get an error like:
var bar = foo(Set() + "test1" + "test2") bar = bar.map(x => x) found : Iterable[String] required: foo bar = bar.map(x => x) ^
The type error is absolutely beautiful (in my understanding). However, I am wondering how to implement a case-wrapper class for a collection so that you can call map, foldLeft, etc. And still get an object of class case. Do I need to override all these functions, or is there some other way?
Edit
I tend to make a RΓ©gis Jean-Gilles decision that works for me. However, after Googling for hours, I found another interesting Scala feature called SetProxy . I could not find trivial examples, so I'm not sure if this trait does what I want:
- a custom type appears, i.e. other type than
Set - the type must be a case class (we want to perform pattern matching)
- we need to "delegate" the map, foldLeft, etc. methods, which should pass a call to our actual set and return the resulting set wrapped arround in a new type
My first idea was to extend Set , but my custom type Foo already extends another class. Therefore, the second idea was to mix Iterable and IterableLike attributes. Now I am blushing about the SetProxy , which made me think about what is the βbestβ way. What are your thoughts and feelings?
Since I started learning Scala three days ago, any pointers have been much appreciated!