[英]How to Pass dynamic type to a method already having generic type in scala
I have a method:我有一个方法:
object Object1{
def method1[T >: Null: ClassTag: TypeTag](input: String): T = {
val m = new ObjectMapper() with ScalaObjectMapper
m.registerModule(DefaultScalaModule)
Option(input)
.map(m.readValue[T](_, classTag[T].runtimeClass.asInstanceOf[Class[T]]))
.orNull
}
}
I want to dynamically pass type to this method, I have tried it like:我想动态地将类型传递给这个方法,我试过这样:
import spark.implicits._
def getHome[T](s: Dataset[Sig], someString: String): Dataset[T] = {
s.filter(s => (s.sType == someString))
.map(s => Object1.method1[T](s.sDetails))
}
But I am getting error: No implicits found for parameter evidence$6 .但我收到错误:没有为参数 evidence$6 找到隐含。 I have also imported implicits.我还导入了implicits。 What is the best way to implement above logic in Scala?在 Scala 中实现上述逻辑的最佳方法是什么?
You are trying to pass a value of a wider type T
to a narrower type T >: Null: ClassTag: TypeTag
and this is never OK.您正在尝试将较宽类型T
的值传递给较窄类型T >: Null: ClassTag: TypeTag
,这永远不会好。 You have to add the same (or better) type constraints to the type parameter of getHome
:您必须向getHome
的类型参数添加相同(或更好)的类型约束:
def getHome[T >: Null: ClassTag: TypeTag](s: Dataset[Sig], someString: String): Dataset[T] = {
It also feels like method1
should be using the Manifest
typeclass rather than ClassTag
and TypeTag
.感觉method1
应该使用Manifest
类型类而不是ClassTag
和TypeTag
。 This might simplify things, so check the docs for ScalaObjectMapper
.这可能会简化事情,因此请查看ScalaObjectMapper
的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.