title: Get the companion object instance of a inner modul with the Scala reflection API
body: <p>I implemented the code mentioned in <a href="https://stackoverflow.com/questions/11020746/get-companion-object-instance-with-new-scala-reflection-api">Get companion object instance with new Scala reflection API</a> (code from here <a href="https://gist.github.com/xeno-by/4985929" rel="nofollow noreferrer">https://gist.github.com/xeno-by/4985929</a>).</p>
  
  <pre><code>object Reflection {
      def getCompanionObject(caseclassinstance:Product):Any = {
          import scala.reflect.runtime.{currentMirror =&gt; cm}
          val classSymbol = cm.classSymbol(caseclassinstance.getClass)
          val moduleSymbol = classSymbol.companionSymbol.asModule
          val moduleMirror = cm.reflectModule(moduleSymbol)
          moduleMirror.instance
      }
  }
  </code></pre>
  
  <p>This works fine for any standard class of case classes. Unfortunately in some classes of the project I get an Exception: <code>scala.ScalaReflectionException: object Tensor is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror</code> The exception is pretty clear, so I tried to change my code as follows: </p>
  
  <pre><code>object Reflection {
      def getCompanionObject(caseclassinstance:Product):Any = {
          import scala.reflect.runtime.{currentMirror =&gt; cm}
          val classSymbol = cm.classSymbol(caseclassinstance.getClass)
          val moduleSymbol = classSymbol.companionSymbol.asModule
          val instanceMirror = cm.reflect(caseclassinstance)
          val moduleMirror = instanceMirror.reflectModule(moduleSymbol)
          moduleMirror.instance
      }
  }
  </code></pre>
  
  <p>But now I get a <code>scala.ScalaReflectionException: expected a member of class Tensor, you provided object Prototype2.SPL.SPL_Exp.Tensor</code> and I did not find out how to change the code to fix this. Any help is greatly appreciated!</p>
  
  <p>Update: I provide some code for better reproducibility:</p>
  
  <pre><code>scala&gt; trait SPL {
       | case class Tensor()
       | }
  defined trait SPL
  
  scala&gt; val s = new SPL {}
  s: SPL = $anon$1@165f5a4
  
  scala&gt; val t = s.Tensor()
  t: s.Tensor = Tensor()
  
  scala&gt; object Reflection { /* as in the first code snippet*/}
  defined module Reflection
  
  scala&gt; Reflection.getCompanionObject(t)
  scala.ScalaReflectionException: object Tensor is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror
  ...
  
  scala&gt; object Reflection { /* as in the second code snippet*/}
  defined module Reflection
  
  scala&gt; Reflection.getCompanionObject(t)
  scala.ScalaReflectionException: expected a member of class Tensor, you provided object SPL.Tensor
  ...
  </code></pre>