【问题标题】:Convert implicit def to scala 3 given syntax将隐式 def 转换为给定语法的 scala 3
【发布时间】:2022-01-16 16:18:27
【问题描述】:

对于以下使用猫效果的随机 UUID 生成器:

import java.util.UUID
import cats.effect.Sync
import cats.ApplicativeThrow

trait UuidGen[F[_]]:
  def make: F[UUID]
  def read(string: String): F[UUID]

object UuidGen:
  def apply[F[_]: UuidGen]: UuidGen[F] = implicitly

  implicit def forSync[F[_]: Sync]: UuidGen[F] =
    new UuidGen[F]:
      def make: F[UUID] = 
        Sync[F].delay(UUID.randomUUID)
      def read(string: String): F[UUID] =
        ApplicativeThrow[F].catchNonFatal(UUID.fromString(string))

scala 3 given 语法中 implicit def 的等价物是什么?

【问题讨论】:

标签: scala implicit scala-3 cats-effect


【解决方案1】:
import java.util.UUID
import cats.effect.Sync
import cats.ApplicativeThrow

trait UuidGen[F[_]]:
  def make: F[UUID]
  def read(string: String): F[UUID]

object UuidGen:
  def apply[F[_]: UuidGen]: UuidGen[F] = summon

  given [F[_]: Sync]: UuidGen[F] with
    def make: F[UUID] =
      Sync[F].delay(UUID.randomUUID)
    def read(string: String): F[UUID] =
      ApplicativeThrow[F].catchNonFatal(UUID.fromString(string))

【讨论】:

  • 上下文语法应该被弃用。
  • @LuisMiguelMejíaSuárez 我不明白您的评论,您能否更具体地指出,究竟应该弃用什么?
  • @AndreyTyukin F[_]: Sync 语法,我个人认为从 Scala 3 开始更好地使用像 (using Sync[F]) 这样的匿名用法 - 但同样,这只是一个个人意见;这就是为什么“应该”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 2013-11-16
  • 2021-12-16
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
相关资源
最近更新 更多