gpt4 book ai didi

scala - Scala缓存是否转换为功能接口(interface)

转载 作者:行者123 更新时间:2023-12-04 00:19:10 25 4
gpt4 key购买 nike

Scala 2.12 可以自动将 lambda 表达式转换为接口(interface)。例如,我正在使用:

import org.apache.kafka.common.serialization.{Deserializer, Serde, Serializer}
import scalapb.GeneratedMessageCompanion

class ProtoSerde[A <: scalapb.GeneratedMessage](implicit companion: GeneratedMessageCompanion[A])
extends Serde[A] {
override def serializer(): Serializer[A] = (_: String, data: A) => data.toByteArray

override def deserializer(): Deserializer[A] = (_: String, data: Array[Byte]) => companion.parseFrom(data)
}

它会自动缓存创建对象的实例,这样就不会在每次调用时分配一个新对象。 IE。我要:

import org.apache.kafka.common.serialization.{Deserializer, Serde, Serializer}
import scalapb.GeneratedMessageCompanion

class ProtoSerde[A <: scalapb.GeneratedMessage](implicit companion: GeneratedMessageCompanion[A])
extends Serde[A] {
lazy val _serializer: Serializer[A] = (_: String, data: A) => data.toByteArray
lazy val _deserializer: Deserializer[A] = (_: String, data: Array[Byte]) => companion.parseFrom(data)

override def serializer(): Serializer[A] = _serializer

override def deserializer(): Deserializer[A] = _deserializer
}

编译器会自动执行此优化,还是我必须自己执行?

最佳答案

def 没有记住调用它每次都会重新计算值。以后可能会被 JIT 编译器优化。

但是有一个更简单的解决方案可以让类的属性被内存。 Scala 允许在覆盖父方法时将 def 更改为 val。也可以在扩展类上添加 lazy 修饰符:

class ProtoSerde[A <: scalapb.GeneratedMessage](implicit companion: GeneratedMessageCompanion[A])
extends Serde[A] {
override lazy val serializer: Serializer[A] = (_: String, data: A) => data.toByteArray

override lazy val deserializer: Deserializer[A] = (_: String, data: Array[Byte]) => companion.parseFrom(data)
}

关于scala - Scala缓存是否转换为功能接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61983239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com