user2221323
user2221323

Reputation: 503

Scala match on generic type

is it possible to match somehow on the return type A and if it is e.g. an int, do a calculation that returns an int. See the following example:

def test[A](a: A):A = a match{
    case b: Int => b * 5
    case _ => a
}

The error message:

type mismatch;  found   : Int  required: A

Thank you!

Upvotes: 0

Views: 461

Answers (2)

Konstantin
Konstantin

Reputation: 3294

you can change return to Any

def test[A](a: A):Any = a match{
  case b: Int => b * 5
  case _ => a
}

another alternative is to do instanceof

case b: Int => (b * 5).asInstanceOf[A]

Upvotes: 2

Impredicative
Impredicative

Reputation: 5069

Yes:

def test(a : Int) = a * 5
def test[A](a : A) = a

Scala supports overloading methods and type-based dispatch, so in this case you don't have to resort to pattern matching.

Upvotes: 0

Related Questions