Goldengirl Goldengirl - 3 months ago 14
Scala Question

How to return Int from an if-else block instead of anyVal in scala?

I am a newbie in Scala. I was trying to use a if-else block in scala to try and return a "Int".

My code looks something likie this:

val blockNumber = {
if(x.getName equals ("NATIVE")) 0
else {
if(x.getName equals ("DATIVE")) 1
}
}


I use this value
blockNumber
in the method
setBlockNumber()
and this where the problem occurs:

new setBlockNumber(Option(blockNumber))


But everytime I try to do this the method gives an error saying :

type mismatch; found : AnyVal required: Int


Can somebody please point out my mistake and how can I rectiy it? Thankyou for your time in advance.

Answer

After reading the comments, I believe what you want is to store an Option[Int] in blockNumber:

val blockNumber = if (x.getName == "NATIVE") {
    Some(0)
} else if (x.getName == "DATIVE") {
    Some(1)
} else {
    None
}

new setBlockNumber(blockNumber)

I would also rewrite this using match:

val blockNumber = x.getName match {
    case "NATIVE" => Some(0)
    case "DATIVE" => Some(1)
    case _ => None
}
new setBlockNumber(blockNumber)
Comments