Scala Reflective Access Warning in Scala

What this warning means:

reflective access to the method of an element of the structural type getMap must be enabled

The warning contains a link to scala docs, but I don’t understand how my code relates to the explanation. (In particular, the explanation reflects reflection ... how does my code use reflection?)

I have this: (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 

A warning is generated here:

 [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] ^ 
+8
scala
source share
1 answer

I think that what happens is that the new { ... } objects are structured, which requires reflection to be implemented.

The main reason is that Scala structural typing allows objects to be processed as if they were instances of many types according to the methods that they actually have (for example, duck printing). The JVM allows you to use only one type, so methods that are not part of the base type of an object must be accessible through something other than a regular call to a virtual method. The mechanism used in this case is a reflection.

When the Scala compiler sees a call to a method called on a structurally typed object, it (modulo some optimizations) translates the method call, for example:

 af(b, c) 

to

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

An example taken from the place where the technique was described .

The Scala team decided to apply a selection policy for advanced features that everyone might not use. reflectiveCalls is one of them, as described in this SIP

+13
source share

All Articles