Pavel
Pavel

Reputation: 1539

scala: Type pattern maching

Another question from the beginner.

I am trying to understand how next piece of code works. Now sure what is the meaning of the second case statement.

   obj match {
        case _: BigInt => Int.MaxValue  
        case BigInt => -1       
    }

In first case I will match object against type BingInt What will be the matching against in the second case?

Upvotes: 1

Views: 114

Answers (1)

manub
manub

Reputation: 4100

The first case matches on any value which is a BigInt. The second case matches on the BigInt companion object.

def test(obj: Any) = obj match {
  case _: BigInt => Int.MaxValue
  case BigInt => -1
}

scala> test(BigInt(1))
res2: Int = 2147483647

scala> test(BigInt)
res3: Int = -1

That said, it's likely that what you really want it's the first case, unless you have any specific reasons to check whether you're passing the BigInt companion object to that pattern match.

Upvotes: 6

Related Questions