简体   繁体   English

Scala:检查通用存在类型

[英]Scala: check generic existential type

I have a Scala library method that I need to override:我有一个需要覆盖的 Scala 库方法:

def transform(dataset: Dataset[_]): DataFrame

What I want to do: in my overridden implementation, check if _ is MyType .我想要做的是:在我覆盖的实现中,检查_ is MyType If yes, cast dataset to Dataset[MyType] .如果是,将datasetDataset[MyType] If not, throw an exception saying type ActualTypeOf_ is not supported .如果不是,则抛出一个异常,指出type ActualTypeOf_ is not supported

There's only one MyType I care about.我只关心一种MyType Obviously, I can't rewrite the library to change method's signature.显然,我不能重写库来更改方法的签名。

As you pointed in a comments section to the question Dataset is actually Spark Dataset.正如您在评论部分指出的问题Dataset实际上是 Spark 数据集。 To be honest, I'm not the Spark expert, but from the doc I see there is method which allows to get Classtag for type T (as far as I understand) : https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Dataset.html#classTag--老实说,我不是 Spark 专家,但从文档中我看到有一种方法可以获取类型T Classtag (据我所知): https : Classtag /api/java/org/apache/spark/sql/Dataset.html#classTag--

So, I think your solution might look like:所以,我认为您的解决方案可能如下所示:

override def transform(dataset: Dataset[_]): DataFrame = {
 val dataClass = dataset.classTag.runtimeClass
 if (dataClass == classOf[MyType]) {
   val myTypeDataset = dataset.as[MyType]
   // further handling of `myTypeDataset`
 } else {
   throw new RuntimeException(s"type $dataClass is not supported")
  }
}

Hope this helps!希望这可以帮助!

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

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