Xtend2: extended type-based collection filters [message #1009819] |
Fri, 15 February 2013 14:26  |
Eclipse User |
|
|
|
Hi all,
I have been using Xtend 2 for a good while now and love it. In the meanwhile
I ported around 400 Xpand files and Java classes so I think I have become
used to it.
Nevertheless I have two questions regarding the collection handling. I think
these points are quite easy to solve (beginner-level), maybe they are even
worth to be added to the documentation as "best practices".
We can use the typeof() method for type-based filters, for example doing
something like this:
val books = myObjects.filter(typeof(Book))
We can also use arbitrary filters by properties or extension methods
val myBooks = books.filter(e|e.active && e.isOwnBook)
(active is a simple property here while isOwnBook is an example for an
extension method)
When working with meta classes it is a very common use case to iterative
over collection subsets based on certain types. For recurring filters we
create extension methods to encapsulate the filter logic. That is all fine.
1. Is it possible to combine multiple types in a filter clause?
For example if I want to get a few sub types of a base class, but not all of
them.
val booksAndPages = myObjects.filter(typeof(Book) || typeof(Page))
Until now I used to work with a helper method for these use cases, like
that:
val booksAndPages = myObjects.filter(e|e.isBookOrPage)
def isBookOrPage(Object it) {
switch (it) {
Book: true
Page: true
default: false
}
}
While the idea of an extension method in general looks not bad to me (see
above) the shown usage of the switch statement admittedly seems not very
elegant, hence I would like to get rid of it.
2. Is it possible to exclude (instead of include) the according type?
Of course this is a special case of question one, but if this is required it
wouldn't be appropriate to select all except one types as this would create
an unrequired maintenance point as this would require that new types are
added to that list always.
Therefore I was curious whether there exists a syntax shorthand for
excluding a type from a collection.
val allExceptBooks = myObjects.filter(!typeof(MyType))
or (using exclude() following Xtend 1)
val allExceptBooks = myObjects.exclude(typeof(MyType))
or (using the minus operator)
val allExceptBooks = myObjects - myObjects.filter(typeof(MyType))
Thanks for your answers,
Axel
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.03306 seconds