简体   繁体   中英

Scala: Using TypeTag in a method

I am trying to write a method like this:

def foo[T:TypeTag](value: Int):String = {
  (/* do something */).mapTo[T].map(_.toJson)
}

where mapTo has the signature:

def mapTo[S](implicit tag: ClassTag[S]): Future[S] = { ... }

using org.scala-lang.scala-reflect to be able to do something like:

foo[String](1) , foo[List[Double]](10) and so on.

I tried to write it in different ways, but I got different compile errors. Is there any way to make something like that to work?

Error:(26, 45) Cannot find JsonWriter or JsonFormat type class for T
    (/* do something */).mapTo[T].map(_.toJson)
                                            ^
Error:(26, 45) not enough arguments for method toJson: (implicit writer: spray.json.JsonWriter[T])spray.json.JsValue.
Unspecified value parameter writer.
    (/* do something */).mapTo[T].map(_.toJson)
                                        ^

This link How to get ClassTag form TypeTag, or both at same time? not clarify what I am after to. It looks like trying to "filter" some information about some class.

If what you need is a ClassTag then why not change the method of foo to have the ClassTag ? Like so:

def foo[T](value: Int)(implicit ev: ClassTag[T]): String ={ ...

That would seem to satisfy your basic need of declaring that there exists a ClassTag in implicit scope.

Edit :

What you're showing has nothing to do with ClassTag and everything to do with the fact that it's missing the implicits for a JsonWriter or a JsonFormat . You're probably missing an import to bring those into scope.

Read the errors: mapTo works. It's toJson which doesn't, and it shouldn't: you can't convert any T with a TypeTag to JSON. Just require that T must have a JsonWriter as well: def foo[T: TypeTag: JsonWriter](value: Int) = ... . You'll also get a Future[String] , not a String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM