如何将下面的java代码转换成kotlin?

vtwuwzda  于 2021-06-04  发布在  Kafka
关注(0)|答案(2)|浏览(365)
  1. consumer.commitAsync(new OffsetCommitCallback() {
  2. public void onComplete(Map<TopicPartition,
  3. OffsetAndMetadata> offsets, Exception e) {
  4. if (e != null)
  5. log.error("Commit failed for offsets {}", offsets, e);
  6. }
  7. });

我从定义到Kafka都得到了上面的代码。我不知道怎么把它们变成Kotlin。我试过了,但失败了。
欢迎任何评论。谢谢
更新
我皈依了

  1. object:OffsetCommitCallback() {
  2. override fun onComplete(offsets:Map<TopicPartition, OffsetAndMetadata>, e:Exception) {
  3. if (e != null) log.error("Commit failed for offsets {}", offsets, e)
  4. }
  5. }

但是我得到了 This class does not have a constructor .
更新
似乎以下工作:

  1. kafkaConsumer.commitAsync(mapOf(k to currentOffsets.get(k)), object:OffsetCommitCallback {
  2. override fun onComplete(offsets:Map<TopicPartition, OffsetAndMetadata>, e:Exception) {
  3. e?.let {
  4. log.error("Commit failed for offsets {}", offsets, e)
  5. }
  6. }
  7. })
jjjwad0x

jjjwad0x1#

看起来像 OffsetCommitCallback 是函数接口,因此您应该能够在函数调用中使用lambda(sam转换):

  1. kafkaConsumer.commitAsync(mapOf(k to currentOffsets[k])) { offsets, e ->
  2. e?.let {
  3. log.error("Commit failed for offsets {}", offsets, e)
  4. }
  5. }
ztigrdn8

ztigrdn82#

看起来像 OffsetCommitCallback 是一个接口,而不是一个类,因此创建它的匿名示例不会使用括号:

  1. object : OffsetCommitCallback { ... }

而不是

  1. object : OffsetCommitCallback() { ... }

还要注意,假设原始代码正在检查 enull ,您可能需要在kotlin方法签名中使用可为null的类型:

  1. override fun onComplete(..., e: Exception?)

相关问题