简体   繁体   中英

What does "reflective access of structural type member method should be enabled..." warning mean in Scala?

After switching to Scala 2.10 I get tons of warnings:

reflective access of structural type member method ... should be enabled by making the implicit value language.reflectiveCalls visible

What does it mean?

The warning actually tells where to look in the documentation for an explanation:

Test.scala:9: warning: reflective access of structural type member method y should be enabled
by making the implicit value language.reflectiveCalls visible.
This can be achieved by adding the import clause 'import scala.language.reflectiveCalls'
or by setting the compiler option -language:reflectiveCalls.
See the Scala docs for value scala.language.reflectiveCalls for a discussion
why the feature should be explicitly enabled.

Referenced Scaladoc entry (be sure to click the |> arrow to the left to expand the documentation entry).

From Scala Docs:

Why control it? Reflection is not available on all platforms. Popular tools such as ProGuard have problems dealing with it. Even where reflection is available, reflective dispatch can lead to surprising performance degradations.

Think about this code that uses an anonymous subclass:

class Student(val id:Int)
val specialStudent = new Student(0) {
   val greeting = "I am a special student with id " + id // Warning: id can be obfuscated
} 

Link to Scala Docs

I ran into this warning with a function I was using to divide an Option[Double or Long] by 100:

  def safeDivideBy100[T <: AnyVal { def toDouble: Double }](number: Option[T]): Option[Double] =
     number match {
       case None    => None
       case Some(x) => Some(x.toDouble / 100)
     }

Fixing it simply required adding to the top of the file:

import scala.language.reflectiveCalls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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