Mr.Turtle
Mr.Turtle

Reputation: 3090

Match on Scala Manifest

I have a method that parses an json to an object. Currently I have two def that does exactly the same thing, except one parses A and the other parses List[A].

This is how it looks like:

def parse[A <: V2Model](mf: Manifest[A]) = {
  // doing parsing
}

def parseList[A <: V2Model](mf: Manifest[List[A]]) = {
  // doing parsing of list
}

It is not very readable to have two of the same ´def´. The manifest is not implicit.

Is there a way to match on Manifest?

I have tried this without success:

def parse[A <: V2Model](mf: Manifest[A]) = {
  mf match {
    case _ : Manifest[List[A]] => // do list parsing
    case _ : Manifest[A] => // do object parsing
  }
}

Upvotes: 0

Views: 105

Answers (2)

Gonzalo Guglielmo
Gonzalo Guglielmo

Reputation: 629

If A is subtype of V2Model, then "mf: Manifest[A]" will never be Manifest[List[A]].

Also there are no common return type between A and List[A], so it's not possible to achieve what you want.

The question is, why you want to behave differently when parsing Lists and when parsing objects? Serialization frameworks already resolve this.

Upvotes: 2

Alexey Romanov
Alexey Romanov

Reputation: 170745

Not in general, but for this case (and still ugly):

if (mf.runtimeClass == classOf[List[_]]) {
  // a list manifest
} else {
  // not a list manifest
}

Upvotes: 1

Related Questions