Offhand, you could do this by changing the signature of between. Instead of taking a range and returning a Boolean, have that return a new class, which has and as a function on that, and have and do the actual calculation.
In other words, something like:
object Helpers
{
class Betweener(value: Int, start: Int) {
def and(end: Int): Boolean = value >= start && value <= end
}
implicit class IntBetween(value: Int)
{
def between(start: Int) = new Betweener(value, start)
}
}
@tmoore: I’ve seen Range some time ago but I guess it slipped my mind. Thank you. However, my question was more about realizing a specific expression in scala.
@siddhartha-gadgil: 1 -> 10 looks really nice. Need to take a closer look at that too. But, as already mentioned, I was actually looking for a possibility to realize a between statement the way I have written it. Thank you though for providing different solutions. To see how scala developers think is a great help when learning this new, beautiful language.
@jducoeur: Thank you! This was the answer I was actually looking for! One small issue bothers me though: Your implementation allows to write 5 between 1 which will return an instance of Betweener. Is there any way to forbid that, i.e. when calling between, one is forced to call and.
so you either work with that precedence (Mark Waks’ solution), or use operators of higher precedence (Siddharta’s solution) or change the order of things (Tim’s solution)
Yes and no. I don’t see any way to force them to do that, but it seems like it should be an error in-context anyway.
That is, the entire point of this is to get a Boolean, right? If you just say 5 between 1, that expression produces a Betweener, not a Boolean, so it should give a compiler error. (Yay for strongly-typed languages.)
So you don’t have to do anything. See this updated version, which shows the compiler error if you uncomment the bit at the end.