Goldengirl
Goldengirl

Reputation: 967

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.

Upvotes: 1

Views: 567

Answers (2)

sascha10000
sascha10000

Reputation: 1230

I just want to clearify why you get AnyVal instead of Int. I don't want to be offensive, but it seems like you are also new to programming...?

Under the assumption that your code would do what you want, your second If is not really senseful. One would write:

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

Which is still AnyVal. Because in the case if either "NATIVE" or "DATIVE" won't match the compiler doesn't know what value you will deliver and therefore it's Unit. The common supertype of Unit and Int is AnyVal.

So your code with missing Paths:

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

So you have basically 2 If-Statements nested in each other. The first one asks if the value of x.getName is "NATIVE" and the other one is an general else path which is normally for handling the default or all other cases. But you put another if in there without an else path which would resolve in Unit. As already stated the common supertype of Int and Unit is AnyVal.

Under the assumption you have only 2 cases "NATIVE" and "DATIVE" you could write:

val blockNumber = if(x.getNmae equal ("NATIVE")) 0
else 1

Otherwise the match-case approach of @Dogbert is the way to go. If there is a possibility that none of the cases could happen you should use Option as @Dogbert did. Otherwise if at least one of your cases will match you may use Int without Option.

Kind regards, hope it helps!

Upvotes: 0

Dogbert
Dogbert

Reputation: 222090

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)

Upvotes: 12

Related Questions