You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala FS2+Circe开发服务遇"No implicit found for evidence"编译错误

问题分析与修复

你的代码存在两个关键问题导致编译错误:

1. stringStreamParser缺少隐式Parser实例

stringStreamParser是circe-fs2提供的字符串转Json流处理工具,它需要一个隐式的io.circe.Parser实例才能工作,你当前代码未引入这个隐式实例,所以编译器报错找不到对应证据。

2. 解码Pipe调用方式错误

你直接把自定义的Decoder[Auth]当作Pipe传给through是错误的,circe-fs2提供的标准解码Pipe是decode[T]方法,它会自动从作用域中读取隐式的Decoder[T]完成解码。


修正后的完整代码

import cats.effect.{IO, IOApp, Temporal}
import cats.effect.std.Console
import cats.effect.kernel.Concurrent
import com.comcast.ip4s.IpLiteralSyntax
import fs2.io.net.Network
import fs2.{Stream, text}
import io.circe.Decoder
import io.circe.fs2._
import io.circe.generic.semiauto.deriveDecoder
// 导入circe默认Parser隐式实例
import io.circe.parser._

object ServerApp extends IOApp.Simple {

  case class Auth(password: String, clientId: String)

  implicit val decoder: Decoder[Auth] = deriveDecoder[Auth]

  override def run: IO[Unit] = cloudServer[IO]

  def cloudServer[F[_]: Concurrent: Console: Network: Temporal]: F[Unit] = {
    Network[F].server(port = Some(port"5555")).map { client =>
      client.reads
        .through(text.utf8.decode)
        .through(stringStreamParser)
        // 改用circe-fs2标准解码方法,自动复用隐式Decoder[Auth]
        .through(decode[Auth])
        .evalTap { auth =>
          Console[F].println(s"Received auth: $auth")
        }
        .handleErrorWith { error =>
          Stream.eval(Console[F].errorln(s"Error processing client: $error"))
        }
    }.parJoinUnbounded.compile.drain
  }
}

改动说明

  • 新增import io.circe.parser._,引入circe默认的Parser隐式实例,解决stringStreamParser的编译错误。
  • 将.through(decoder[F, Auth])替换为.through(decode[Auth]),使用circe-fs2提供的标准解码Pipe,它会自动调用你定义的implicit val decoder: Decoder[Auth]完成类型转换。

修改后代码即可正常编译运行,实现接收JSON消息并解码为Auth实例的功能。

内容的提问来源于stack exchange,提问作者Jelly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:53:11