英文:
what can be used as an alternative to Object in Kotlin?
问题
我正在编写以下的Kotlin代码,但在编译时出现了错误:
``` Null can not be a value of a non-null type ByteArray```
这是我的代码:
fun myKafkaProducer(): MessageBusProducer<UUID?, Any>? {
return if (serverProperties().isWAPKafkaSet) {
val uuidSerializer = UUIDSerializer()
val uuidDeserializer = UUIDDeserializer()
val topic = serverProperties().hmsTopic
val serializer = KafkaProperties.Serializers(Function<UUID, ByteArray> { uuid: UUID? -> uuidSerializer.serialize(null, uuid) }, label@ Function<Any, ByteArray> { sapMessage: Any ->
try {
return@label ObjectMappers.getObjectMapper().writeValueAsString(sapMessage).toByteArray()
} catch (e: JsonProcessingException) {
e.printStackTrace()
}
null /在这里显示错误/
}, null,
null
)
// 在环境中设置WapKafkaHostPortAddress(配置存储库)
return KafkaMessageBusProducerFactory.Builder<UUID, Any>()
.kafkaAddressPropertyName("portAddress"
英文:
I am writing the following Kotlin code but when I compile it gives the error
Null can not be a value of a non-null type ByteArray
this is my code
fun myKafkaProducer(): MessageBusProducer<UUID?, Any>? {
return if (serverProperties().isWAPKafkaSet) {
val uuidSerializer = UUIDSerializer()
val uuidDeserializer = UUIDDeserializer()
val topic = serverProperties().hmsTopic
val serializer = KafkaProperties.Serializers(Function<UUID, ByteArray> { uuid: UUID? -> uuidSerializer.serialize(null, uuid) }, label@ Function<Any, ByteArray> { sapMessage: Any ->
try {
return@label ObjectMappers.getObjectMapper().writeValueAsString(sapMessage).toByteArray()
} catch (e: JsonProcessingException) {
e.printStackTrace()
}
null /*showing error here */
}, null,
null
)
// set WapKafkaHostPortAddress in env (configuration repo)
return KafkaMessageBusProducerFactory.Builder<UUID, Any>()
.kafkaAddressPropertyName("portAddress")
.topic(topic)
.messageBusTypeSerializers(serializer)
.build().create(true)
} else {
return null
}
}
I am trying to code the equivalent of Serializers<UUID, Object>
what other datatype can I use ?
答案1
得分: 1
在 Kotlin 中,Object
的等价类型是 Any?
。只有这样,您才能返回 null,因为类型 Any
是非可空的,而 Any?
可以为 null。
英文:
The equivalent of Object
in Kotlin is the type Any?
. Only then are you able to return null, because the type Any
is non-nullable and Any?
can be null.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论