我使用的是Micrometer Cloudwatch 1.1.3,它以compile 'io.micrometer:micrometer-registry-cloudwatch:1.1.3'
的形式随Gradle一起提供
在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?
答案 0 :(得分:1)
要在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
}