How to convert the following piece of java to kotlin?

huangapple go评论80阅读模式
英文:

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&lt;TopicPartition,
    OffsetAndMetadata&gt; offsets, Exception e) {
        if (e != null)
            log.error(&quot;Commit failed for offsets {}&quot;, 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&lt;TopicPartition, OffsetAndMetadata&gt;, e:Exception) {
    if (e != null) log.error(&quot;Commit failed for offsets {}&quot;, 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&lt;TopicPartition, OffsetAndMetadata&gt;, e:Exception) {
    e?.let {
      log.error(&quot;Commit failed for offsets {}&quot;, 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 -&gt;
    e?.let {
      log.error(&quot;Commit failed for offsets {}&quot;, 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?)

huangapple
  • 本文由 发表于 2020年8月21日 03:46:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63512200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定