【问题标题】:Where is the scaladoc for scala.language.existentials?scala.language.existentials 的 scaladoc 在哪里?
【发布时间】:2023-04-03 16:24:01
【问题描述】:

当我尝试编写一个接受任何Class[_] 作为参数的类时:

case class A(klass: Class[_])

我收到了这个错误:

test.scala:1: 警告:推断存在类型 Option[Class[_$1]] forSome { type $1 },不能用通配符表示,应该 通过使隐式值 scala.language.existentials 启用 可见的。这可以通过添加导入子句'import scala.language.existentials' 或通过设置编译器选项 -语言:存在主义。请参阅 Scala 文档以获取值 scala.language.existentials 以讨论为什么该功能应该是 明确启用。案例类A(类:类[]) ^ 发现一个警告

我很想知道为什么它不起作用。但是“价值 scala.language.existentials 的 Scala 文档”在哪里?我用谷歌搜索了“scaladoc scala.language.existentials”,但有一些我无法理解的线程。

澄清:我知道实现此类的“正确”方法是:

case class A[T](klass: Class[T])

但我想知道警告信息的含义。

【问题讨论】:

    标签: scala existential-type


    【解决方案1】:

    在这种情况下,您要查找的是ClassTag

    class A[T](implicit val tag : reflect.ClassTag[T])
    

    这为您提供了通用参数的ClassTag 对象,您可以使用该对象访问创建对象时给出的Class

    关于existentials,你可以检查:

    【讨论】:

    • 我不明白。我的case class A[T](klass: Class[T]) 工作正常。 ClassTag有什么优势?
    • @LaiYu-Hsuan,如果你写class A[T: ClassTag](和答案一样),你可以这样创建这个类:new A[String],而不是这样:new A(classOf[String]) ,因为编译器会自动为您提供ClassTag 的值。这是获取类型变量的运行时类的惯用方法。而且您始终可以从ClassTag[T] 检索Class[_]
    • 有道理。感谢您的回答。
    【解决方案2】:

    Heather Miller 刚刚在 scala-user 上解释说,您使用左侧窗格搜索“语言”,然后使用右侧窗格搜索存在,因为左侧窗格不包含成员。

    如果您发现一个您不理解的讨论,那么您就知道您来对地方了。

    【讨论】:

      【解决方案3】:

      我有同样的问题,我点击了这个 SO 线程;没有一个答案是对这个问题的直接答案,所以我将在下面添加。 scala.language.existentials 值的 Scala 文档可能在 JavaDoc cmets 中,其中指出:

       /** Only where enabled, existential types that cannot be expressed as wildcard
         *  types can be written and are allowed in inferred types of values or return
         *  types of methods. Existential types with wildcard type syntax such as `List[_]`,
         *  or `Map[String, _]` are not affected.
         *
         *  '''Why keep the feature?''' Existential types are needed to make sense of Java’s wildcard
         *  types and raw types and the erased types of run-time values.
         *
         *  '''Why control it?''' Having complex existential types in a code base usually makes
         *  application code very brittle, with a tendency to produce type errors with
         *  obscure error messages. Therefore, going overboard with existential types
         *  is generally perceived not to be a good idea. Also, complicated existential types
         *  might be no longer supported in a future simplification of the language.
         *
         *  @group production
         */
        implicit lazy val existentials: existentials = languageFeature.existentials
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-25
        • 1970-01-01
        • 2016-01-20
        • 1970-01-01
        相关资源
        最近更新 更多