什么可以用作Kotlin中Object的替代方案?

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

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&lt;UUID, Any&gt;()
            .kafkaAddressPropertyName(&quot;portAddress&quot;
英文:

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&lt;UUID?, Any&gt;? {
         return if (serverProperties().isWAPKafkaSet) {
            val uuidSerializer = UUIDSerializer()
            val uuidDeserializer = UUIDDeserializer()
            val topic = serverProperties().hmsTopic
            val serializer = KafkaProperties.Serializers(Function&lt;UUID, ByteArray&gt; { uuid: UUID? -&gt; uuidSerializer.serialize(null, uuid) }, label@ Function&lt;Any, ByteArray&gt; { sapMessage: Any -&gt;
                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&lt;UUID, Any&gt;()
                    .kafkaAddressPropertyName(&quot;portAddress&quot;)
                    .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.

huangapple
  • 本文由 发表于 2020年8月27日 00:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63602197.html
匿名

发表评论

匿名网友

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

确定