Scala编译器说"T没有可用的TypeTag".在使用泛型的方法中 [英] Scala compiler says "No TypeTag available for T" in method using generics

查看:322
本文介绍了Scala编译器说"T没有可用的TypeTag".在使用泛型的方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码未编译:

override def read[T <: Product](collection : String): Dataset[T] = {
  val mongoDbRdd = MongoSpark.load(sparkSession.sparkContext,MongoDBConfiguration.toReadConfig(collection))
  mongoDbRdd.toDS[T]
}

这是"toDS"定义:

This is "toDS" definition:

def toDS[T <: Product: TypeTag: NotNothing](): Dataset[T] = mongoSpark.toDS[T]()

编译器说:

Error:(11, 20) No TypeTag available for T
    mongoDbRdd.toDS[T]

Error:(11, 20) not enough arguments for method toDS: (implicit evidence$3: reflect.runtime.universe.TypeTag[T], implicit evidence$4: com.mongodb.spark.NotNothing[T])org.apache.spark.sql.Dataset[T].
Unspecified value parameters evidence$3, evidence$4.
    mongoDbRdd.toDS[T]

第11行是mongoDbRdd.toDS[T]

我真的不知道Scala Generics是怎么回事,编译器不是很具体,知道吗?

I really don't know what's going on with Scala Generics and the compiler is not very specific, any idea?

推荐答案

问题在于toDS要求的T的类型约束:

The problem is with the type constraints on T that toDS requires:

// The ':' constraint is a type class constraint.
def toDS[T <: Product: TypeTag: NotNothing](): Dataset[T] =
  mongoSpark.toDS[T]()

// The below is exactly the same as the above, although with user-defined
// names for the implicit parameters.
// All a type class does is append implicit parameters to your function.
def toDS[T <: Product]()(implicit typeTag: TypeTag[T], notNothing: NotNothing[T]) =
  mongoSpark.toDS[T]()

您会注意到这是编译器错误显示的内容-名称扩展为evidence$3evidence$4.

You'll notice that's what your compiler error shows - with the names expanded to evidence$3 and evidence$4.

如果要编译方法,只需添加相同类型的类:

If you want your method to compile, simply add the same type classes:

override def read[T <: Product: TypeTag: NotNothing](
    collection : String): Dataset[T] = { /* impl */ }

这篇关于Scala编译器说"T没有可用的TypeTag".在使用泛型的方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆