monster
monster

Reputation: 1782

Scala: AnyVal usage

I am setting a val in Scala using an if statement, I only want to set the val when certain criteria is met and I would like it to be an Int. I use/compare the val later on with another Int which is (currently) always positive:

val transpose = if(x < y) 10 else -1
...
if(transpose > min) doSomething

I do not like this code because, in the future, min may in fact be negative.

I have changed the if statement to:

val transpose = if(x < y) 10

This returns a type AnyVal. I am wondering how I can utilise this? I still wish to compare the value held within the AnyVal with min but only if it is an Int, otherwise, I want to continue as if the if statement was unsuccessful. In pseudo-code:

if(transpose instanceOf(Int) && transpose > min) doSomething

I have toyed with using transpose.getClass but it just seems like the wrong way to do it.

Upvotes: 2

Views: 149

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37822

Either use an Option, as suggested by Ende Neu:

val transpose = if(x < y) Some(10) else None
if(transpose.exists(_ > min)) doSomething

Or, just use Int.MinValue:

val transpose = if(x < y) 10 else Int.MinValue
if(transpose > min) doSomething // won't doSometihng for any "min" if x < y

Another good option is to make transpose a function of type Int => Boolean (assuming it's only used for this if statement), thus not needing a type to represent the threshold:

val transpose: Int => Boolean = m => if (x < y) 10 > m else false 
if(transpose(min)) doSomething

Upvotes: 3

Related Questions