Goldengirl Goldengirl - 1 year ago 67
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
in the method
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 Source

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

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

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)