简体   繁体   English

Scala:在方法中使用TypeTag

[英]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: 其中mapTo具有签名:

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

using org.scala-lang.scala-reflect to be able to do something like: 使用org.scala-lang.scala-reflect能够执行以下操作:

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

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? 此链接如何同时从TypeTag获得ClassTag或同时获得二者? 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 ? 如果您需要的是ClassTag那么为什么不更改foo的方法以拥有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. 这似乎可以满足您声明隐式范围中存在ClassTag基本需求。

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 . 您所显示的内容与ClassTag无关,并且与它缺少JsonWriterJsonFormat的隐式事实JsonFormat You're probably missing an import to bring those into scope. 您可能缺少导入内容以将其纳入范围。

Read the errors: mapTo works. 读取错误: mapTo有效。 It's toJson which doesn't, and it shouldn't: you can't convert any T with a TypeTag to JSON. toJson ,不是,它不应该:您不能将任何带有TypeTag T转换为JSON。 Just require that T must have a JsonWriter as well: def foo[T: TypeTag: JsonWriter](value: Int) = ... . 只需要求T必须具有JsonWriterdef foo[T: TypeTag: JsonWriter](value: Int) = ... You'll also get a Future[String] , not a String . 您还将获得Future[String]而不是String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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