I want to get the instance of this Interface KotlinDecompilerService
https://github.com/JetBrains/kotlin/blob/master/idea/src/org/jetbrains/kotlin/idea/internal/KotlinDecompilerService.kt in Groovy.
I try:
final KotlinDecompilerService decompilerService =
KotlinDecompilerService.Companion.getInstance()
But the Groovy KotlinDecompilerService.Companion
returns a java.lang.Class
instance.
(The static field and the class have the same name Companion
)
2017-06-24 23:31:59,066 [9849885] ERROR - llij.ide.plugins.PluginManager - Cannot cast object 'class org.jetbrains.kotlin.idea.internal.KotlinDecompilerService$Companion' with class 'java.lang.Class' to class 'org.jetbrains.kotlin.idea.internal.KotlinDecompilerService$Companion'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class org.jetbrains.kotlin.idea.internal.KotlinDecompilerService$Companion' with class 'java.lang.Class' to class 'org.jetbrains.kotlin.idea.internal.KotlinDecompilerService$Companion'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:405)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:319)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:232)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:603)
I have to use reflection to get the instance.
final KotlinDecompilerService decompilerService =
KotlinDecompilerService.Companion.newInstance().getInstance()
It works, but I just wonder if there is a better way.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
The companion objects can access private members of the class. Hence, they can be used to implement the factory method patterns.
Much like Ruby's mixins, Kotlin also bypasses the need for crazy inheritance chains and allows us a more flexible way to define behaviours on our classes by allowing interfaces to not just enforce, but also define the methods for our classes to use.
Object expressions are executed (and initialized) immediately, where they are used. Object declarations are initialized lazily, when accessed for the first time. A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.
you can access member fields directly by @
since it always ref the class rather than its instance in groovy. for example:
def decompilerService = [email protected]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With