简体   繁体   English

如何使这种情况更像Scala

[英]How to make this condition more Scala-like

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). 但这看起来太像Java(如果我使用Ruby,我会在范围上进行切换/案例,然后进行其他比较)。 Is there a more funcional way to do this in Scala? 在Scala中,还有其他更实用的方法吗?

The behavior is quite simple: 行为非常简单:

  • if input is page 1 and total pages is 3, the output is [2] 如果输入是第1页,总页数是3,则输出是[2]
  • if input is page 2 and total pages is 3, the output is [1,3] 如果输入是第2页,总页数是3,则输出是[1,3]
  • if input is page 3 and total pages is 3, the output is [2] 如果输入是第3页,总页数是3,则输出是[2]

I'm looking for an idiomatic solution, I'm still new to Scala. 我正在寻找惯用的解决方案,但我还是Scala的新手。

It would be lovely if I could do something like: 如果可以做类似的事情,那将是很可爱的:

( 1 until 3 ).hasNext( 2 )

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))
    }
}
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))

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 . 它并不单分页范围内的工作,要么,因为一个错误的sliding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM