Typically Typed Classes in Collections in Scala

I have a problem with a generic class that I create in Scala. I have the following class:

class Channel[T, U](val endPoint : EventSource[U], val filter : Occurrence[T] => Boolean, val map : Occurrence[T] => Occurrence[U]) { def send(occurrence : Occurrence[T]) { if (filter(occurrence)) { endPoint.occur(map(occurrence)) } } } 

Here, the channel [T, U] can be considered as a way of distributing Occurrence [T] from EventSource [T] to EventSource [U]. An entry is sent only if the filter function is true, and if this event is transmitted to the card, and the result is sent.

This class seems to be compiling and working correctly. My problem is that I want to connect several channels to an instance of EventSource [T] so that it can distribute Occurrences to several different EventSources of different types. My confusion is basically how to do this:

 class EventSource[T] { var List[Channel[T,U]] list = ... } 

What is here? T simply refers from type T to the EventSource to which list belongs (is a member).

Sorry if this is vague or confusing!

EDIT: I should have noticed that I also want to add this list to the list:

 list = list ++ List[Channel[T, U](new Channel[T, U](endPoint, filter, map)) 

Is adding a real problem?

+4
source share
2 answers

To support typing, you really need to use the wild card _ type . This allows you to define the list in such a way that you take care of the channel type parameter U when adding it to the list, but not when sending an event to all channels in the list. The following compilation, but in its current form is rather circular. You need an additional channel class that does something else than send it to another EventSource.

 class Occurrence[T] class Channel[T, U](val endPoint : EventSource[U], val filter : Occurrence[T] => Boolean, val map : Occurrence[T] => Occurrence[U]) { def send(occurrence : Occurrence[T]) { if (filter(occurrence)) endPoint.occur(map(occurrence)) } } class EventSource[T] { var list: List[Channel[T,_]] = Nil def addChannel[U]( endPoint : EventSource[U], filter : Occurrence[T] => Boolean, map : Occurrence[T] => Occurrence[U]) { list = list ++ List[Channel[T, U]](new Channel[T, U](endPoint, filter, map)) } def occur( occurrence : Occurrence[T] ) { list foreach { _.send( occurrence ) } } } 
+1
source

If I understand your problem correctly, you can use Any:

 class EventSource[T] { val list: List[Channel[T, Any]] = ... 

EDIT: Is your sample code where you use append copied? Because I noticed that you are missing types for the channel. Alternatively, if you just want to add one item to your list, you can use cons, which adds a new item to the top of your list:

 Channel[Your, Types](your, para, meters)::list 

If for some reason you absolutely want to add a new item at the end of this list, you can use :+ .

+2
source

Source: https://habr.com/ru/post/1383897/


All Articles