Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interoperability: how to declare a compile-time array constant in Kotlin?

Tags:

java

kotlin

I’ve got this Java annotation declaration and want to use it in Kotlin

class CurlCommand {
    Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
    var groups: Array<String>? = null
}

The compiler reports TYPE_MISMATCH Required: kotlin.Array<kotlin.String> Found: kotlin.String

I’ve tried

Parameter(names = Array<String>(1, {i-> "-groups"}), description = "Comma-separated list of group names to be run")
var groups: Array<String>? = null

and got “Error:(20, 23) Kotlin: An annotation parameter must be a compile-time constant”

How can I satisfy the Kotlin compiler?

Java simply accepts

@Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
public String groups;
like image 479
Alex Avatar asked Apr 10 '15 12:04

Alex


2 Answers

You declare a constant in Kotlin like so:

const val LG_PACKAGE = "com.myapp"

However, the kotlin documentation for compile-time constants says that they can only be of type String or a primitive type. So the closest you can get if you want to use constants is this:

const val LG_PACKAGE = "com.myapp"

@EnableJpaRepositories(basePackages = arrayOf(LG_PACKAGE))
@EntityScan(basePackages = arrayOf(LG_PACKAGE))
open class LgApp {
like image 52
CorayThan Avatar answered Sep 20 '22 08:09

CorayThan


Sometimes the answer is very simple, once one discovers it accidently

array("-groups")

Although the Kotlin converter gave me this code

@Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
public String groups;

as I’ve mentioned above.

like image 36
Alex Avatar answered Sep 18 '22 08:09

Alex