英文:
How to convert the following piece of java to kotlin?
问题
consumer.commitAsync(mapOf(k to currentOffsets.get(k)), object: OffsetCommitCallback {
override fun onComplete(offsets: Map<TopicPartition, OffsetAndMetadata>, e: Exception) {
e?.let {
log.error("Commit failed for offsets {}", offsets, e)
}
}
})
英文:
consumer.commitAsync(new OffsetCommitCallback() {
public void onComplete(Map<TopicPartition,
OffsetAndMetadata> offsets, Exception e) {
if (e != null)
log.error("Commit failed for offsets {}", offsets, e);
}
});
I got the above piece of codes from definition to kafka. I have no idea how to convert them into kotlin. I tried, but failed.
Any comments welcomed. Thanks
UPDATE
I converted to
object:OffsetCommitCallback() {
override fun onComplete(offsets:Map<TopicPartition, OffsetAndMetadata>, e:Exception) {
if (e != null) log.error("Commit failed for offsets {}", offsets, e)
}
}
but got This class does not have a constructor
.
UPDATE
it seems that the following work:
kafkaConsumer.commitAsync(mapOf(k to currentOffsets.get(k)), object:OffsetCommitCallback {
override fun onComplete(offsets:Map<TopicPartition, OffsetAndMetadata>, e:Exception) {
e?.let {
log.error("Commit failed for offsets {}", offsets, e)
}
}
})
答案1
得分: 1
看起来`OffsetCommitCallback`是一个*函数接口*,因此您应该能够在函数调用中使用lambda表达式([SAM转换][2]):
kafkaConsumer.commitAsync(mapOf(k to currentOffsets[k])) { offsets, e ->
e?.let {
log.error("Commit failed for offsets {}", offsets, e)
}
}
英文:
It looks like OffsetCommitCallback
is a functional interface, so you should be able to use a lambda in your function call (SAM conversion):
kafkaConsumer.commitAsync(mapOf(k to currentOffsets[k])) { offsets, e ->
e?.let {
log.error("Commit failed for offsets {}", offsets, e)
}
}
答案2
得分: 0
看起来 OffsetCommitCallback
是一个接口,而不是一个类,因此创建一个匿名实例时不需要使用括号:
object : OffsetCommitCallback { ... }
而不是
object : OffsetCommitCallback() { ... }
另请注意,鉴于原始代码正在检查 e
是否为 null
,您可能需要在 Kotlin 方法签名中使用可空类型:
override fun onComplete(..., e: Exception?)
英文:
It looks like OffsetCommitCallback
is an interface, not a class, so creating an anonymous instance of it would not use parentheses:
object : OffsetCommitCallback { ... }
rather than
object : OffsetCommitCallback() { ... }
Note also that, given that the original code is checking whether or not e
is null
, you probably need to use a nullable type in your Kotlin method signature:
override fun onComplete(..., e: Exception?)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论