Reputation: 40333
I have the following method:
def generateAssociatedImages : List[ImageFileEntry] = {
if ( this.page > 1 && this.page < this.fileEntry.pageCount ) {
List( copyWithPage( this.page - 1 ), copyWithPage( this.page + 1 ) )
} else {
if ( page == 1 && page != file.fileEntry.pageCount ) {
List( copyWithPage( this.page + 1 ) )
} else {
List( copyWithPage( this.page - 1 ) )
}
}
}
But this one looks too much like Java (if I was using Ruby I'd do a switch/case on a range and then do the other comparisons). Is there a more funcional way to do this in Scala?
The behavior is quite simple:
I'm looking for an idiomatic solution, I'm still new to Scala.
It would be lovely if I could do something like:
( 1 until 3 ).hasNext( 2 )
Upvotes: 1
Views: 189
Reputation: 297265
Are you looking for the adjacent pages?
val pages = 1 to this.fileEntry.pageCount
implicit def toNext(r: Range) = new {
def next(n: Int) = r.view sliding 2 find (n == _.head) map (_.last)
}
def adjacent(page: Int) = List(pages next page, pages.reverse next page).flatten
def generateAssociatedImages : List[ImageFileEntry] =
adjacent(this.page) map copyWithPage
It's a bit of an over-engineering, I admit. But it is elegant. It doesn't work for single-paged ranges either, because of a bug in sliding
.
Upvotes: 0
Reputation: 2104
def ifTrue[T](c : Boolean, v : =>T) = if (c) Some(v) else None
def generateAssociatedImages = List(ifTrue(this.page > 1, -1)), ifTrue(this.page < this.fileEntry.pageCount, 1)).flatten.map(d => copyWithPage(this.page + d))
Upvotes: 2
Reputation: 24769
Assuming that on a one page, the list of images is empty, you can have the following:
def generateAssociatedImages: List[ImageFileEntry] = {
val pageCount = fileEntry.pageCount
page match {
case `pageCount` if page == 1 => List()
case `pageCount` => List(copyWithPage(pageCount - 1))
case 1 => List(copyWithPage(2))
case x => List(copyWithPage(x - 1), copyWithPage(x + 1))
}
}
Upvotes: 7