Shorter sntax for Kotlin/Java class reference

When we need to access class we must write whole ‘java reflection syntax’.
SettingsAbc::class.java

It would be nice to have shorter syntax for this case - simple use a class name (this is implemented in some languages and works quite well).
SettingsAbc

It could be java class by default or KClass if compiller is able to inffer it from context

I believe that using simply class name is very expresive, so I wonder could we implement this in Kotlin or are there any issues with such approach?

The SettingsAbc expression already has a meaning in the current version of Kotlin: it’s a reference to the companion object of the SettingsAbc class.

It may be worthwhile to allow shorthand in annotations only (as objects cannot be the value of an annotation).

I while ago I proposed a few syntax options like:

SettingsAbc::jclass

If I remember correctly the push back at the time was that this was that this was “JVM platform only” and that didn’t sit well with the Kotlin team. To me ::class.java is “JVM only” and a nicer short syntax would be very welcome for those development shops where JVM is the main target.

3 Likes

Up until first Release Candidate there were nice helper methods like this (IIRC):

javaClass <SettingsAbc>()
myInstance.javaClass

Not sure the reasoning for getting rid of them, the announcement gave no reasoning. If you wanted sonething like them they are trivial to implement using reified inline functions:

Actually, as you can see from the code fragment you’ve posted, T.javaClass is no longer deprecated in 1.1. The javaClass<T>() function was removed a long time ago, before 1.0.

T.javaClass is an instance method (so not particularly useful for the “Java class literal” case).

We still need to use SettingsAbc::class.java at this point right? Has anyone got an improvement on that?

No, ::class.java is the intended way to access the Java class for a given Kotlin type. As an improvement, you can usually define a wrapper with a reified type parameter:

inline fun <reified T : Any> wrap() { originalFunction(T::class.java) }

Also note that annotations use the regular ::class syntax, not ::class.java.

We have no plans to add a shorter syntax such as ::jclass. While ::class.java is indeed JVM-only, the only JVM-only part is the .java property, which is defined in the standard library, not in the language itself, and there’s nothing wrong with having JVM-only parts in the library. ::jclass would be a Java-specific keyword in the core language, which we do not want to have.