我正在使用随Gradle作为compile 'io.micrometer:micrometer-registry-cloudwatch:1.1.3'
引入的Micrometer Cloudwatch 1.1.3
在Java中,我可以通过执行以下操作创建CloudWatchConfig
:
CloudWatchConfig cloudWatchConfig = new CloudWatchConfig() {
@Override
public String get(String s) {
return "my-service-metrics";
}
@Override
public boolean enabled() {
return true;
}
@Override
public Duration step() {
return Duration.ofSeconds(30);
}
@Override
public int batchSize() {
return CloudWatchConfig.MAX_BATCH_SIZE;
}
};
我认为Kotlin中的等效项应该是:
val cloudWatchConfig = CloudWatchConfig {
fun get(s:String) = "my-service-metrics"
fun enabled() = true
fun step() = Duration.ofSeconds(30)
fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
}
Koltin编译器未能通过此操作,指出了该块的最后一行:
fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
说它期望一个String类型的值?经过大量调试后,我能够通过返回step函数的toString来解决此问题。您不能只传递任何字符串,因为它将像由Duration生成的那样进行解析。我的Kotlin代码现在可以正常工作,如下所示:
val cloudWatchConfig = CloudWatchConfig {
fun get(s:String) = "my-service-metrics"
fun enabled() = true
fun step() = Duration.ofSeconds(30)
fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
step().toString()
}
在查看了CloudWatchConfig,StepRegisteryConfig和MeterRegistryConfig接口之后,我不知道为什么会这样。为什么Koltin会这样做,为什么会期望持续时间的toString?
最佳答案
要在Java中创建等效于匿名类的语法,其语法略有不同。您需要使用object
关键字,并且还包括用于接口方法的override
关键字。例如
val cloudWatchConfig = object : CloudWatchConfig {
override fun get(key: String) = "my-service-metrics"
override fun enabled() = true
override fun step() = Duration.ofSeconds(30)
override fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
}