Visual Sharp
Visual Sharp

Reputation: 3986

C# nameof(Class) equivalent in Kotlin

In C# we have nameof() operator which return name of the class in string, what is the equivalent in Kotlin?

My use case would be something like this for

internal val TAG = nameof(MyCustomActivity)

Upvotes: 8

Views: 1943

Answers (2)

Dan Lugg
Dan Lugg

Reputation: 20592

As mentioned in the accepted answer, the <class>::class.simpleName property will provide a result similar to that of the C# nameof operator. However, unlike nameof, ::class.* cannot be evaluated at compile-time.

This is relevant, as cases where you may use the nameof operator in C#, you cannot equivalently do with ::class

For example, AspectJ's @Around annotation.

The following will fail, as you cannot interpolate non-compile-time expressions:

@Around("@annotation(${MyAnnotation::class.simpleName})")

If Kotlin supported nameof in the same fashion as C# (where it can be used in that context) one could do this:

@Around("@annotation(${nameof(MyAnnotation)})")

So, while the accepted answer provides a functionally similar manner of resolving symbol names in Kotlin, it cannot be used with the same flexibility as nameof in C#.


Interestingly, until writing this answer I didn't realize you can interpolate constant value (and other compile-time evaluable) expressions into annotation parameters; the following will compile:

const val FOO = "foo"

@MyAnnotation("${FOO} ${1 + 1}")

Upvotes: 10

Trevor
Trevor

Reputation: 1451

MyCustomActivity::class.simpleName

Will output MyCustomActivity

MyCustomActivity::class.qualifiedName

Will output <your_package>.MyCustomActivity

Upvotes: 7

Related Questions