【问题标题】:Warning about reflective access of structural type member in Scala关于 Scala 中结构类型成员的反射访问的警告
【发布时间】:2014-11-06 19:31:44
【问题描述】:

这个警告是什么意思:

应该启用结构类型成员方法getMap的反射访问

警告包括对 scala 文档的引用,但我不明白我的代码与解释有何关联。 (具体解释中提到了反射……我的代码是如何使用反射的?)

我有这个:(Scala 2.11.2)

object getMap {
    implicit def fromOptionToConvertedVal[T](o:Option[T]) = new {
        def getMap[R] (doWithSomeVal:(T) => R) = new {
            def orElse(handleNone: => R) = o match {
                case Some(value) => doWithSomeVal(value)
                case None => handleNone
            }
        }
    }   
}

import getMap._
val i:Option[Int] = Some(5)
val x = i getMap (_*2) orElse 1

这会产生以下警告:

[warn] /Users/Greg/git/Favorites-Demo/src/main/scala/com/rs/server/ThriftServer.scala:34: reflective access of structural type member method getMap should be enabled
[warn] by making the implicit value scala.language.reflectiveCalls visible.
[warn] This can be achieved by adding the import clause 'import scala.language.reflectiveCalls'
[warn] or by setting the compiler option -language:reflectiveCalls.
[warn] See the Scala docs for value scala.language.reflectiveCalls for a discussion
[warn] why the feature should be explicitly enabled.
[warn] val x = i getMap (_*2) orElse 1
[warn]           ^
[warn] /Users/Greg/git/Favorites-Demo/src/main/scala/com/rs/server/ThriftServer.scala:34: reflective access of structural type member method orElse should be enabled
[warn] by making the implicit value scala.language.reflectiveCalls visible.
[warn] val x = i getMap (_*2) orElse 1
[warn]                        ^

【问题讨论】:

    标签: scala


    【解决方案1】:

    我认为发生了什么是 new { ... } 对象是结构类型的,需要反射来实现。

    根本原因是 Scala 结构类型允许根据对象实际拥有的方法(如鸭子类型)将对象视为多种类型的实例。 JVM 只允许一种类型,因此不属于对象底层类型的方法必须通过普通虚拟方法调用以外的方式访问。在这种情况下使用的机制是反射。

    当 scala 编译器看到对结构类型对象调用的方法调用时,它(以一些优化为模)转换方法调用,如下所示:

    a.f(b, c)
    

    a.getClass
        .getMethod("f", Array(classOf[B], classOf[C]))
        .invoke(a, Array(b, c))
    

    示例取自the place where the technique was described

    Scala 团队决定对高级功能实施选择加入政策。 reflectiveCalls 恰好是其中之一,如 SIP 中所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-31
      • 2021-01-03
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多