首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala单例对象与隐式解析

Scala单例对象与隐式解析
EN

Stack Overflow用户
提问于 2020-08-04 13:17:20
回答 1查看 153关注 0票数 0

在scala中实现隐式解析的最佳方法是什么?这在Either和自定义错误对象中尤为常见。

在下面的代码示例中,一个方法返回以IO包装的特定于应用程序的错误。错误由扩展Throwable的单例对象表示。这段代码没有编译,因为scala正在寻找隐式的AppSpecificError.type而不是Throwable

可以将所有内容都放入指定类型的变量中,但看起来很奇怪。这似乎是一个相当常见的情况,什么是最好的方式来解决它?

代码语言:javascript
复制
import cats.data.EitherT
import cats.effect.IO
import cats.implicits._

import scala.util.Random

object EitherTest {

  case object AppSpecificError extends Throwable

  def random: IO[Boolean] = {
    IO(Random.nextBoolean())
  }

  def appMethod(flag: Boolean): EitherT[IO, Throwable, Int] = {
    for {
      flag <- EitherT.right(random)
      result <- if (flag) {
        EitherT.left[Int](AppSpecificError.pure[IO]) // compilation error here
      } else {
        EitherT.right[Throwable](10.pure[IO])
      }
      // can be more computations here
    } yield result
  }

  def main(args: Array[String]): Unit = {
    appMethod(true).value.unsafeRunSync() match {
      case Right(s) => println("Success")
      case Left(error) => println(error)
    }
  }
}
代码语言:javascript
复制
Error:(18, 14) type mismatch;
 found   : cats.data.EitherT[cats.effect.IO,_1,Int] where type _1 >: EitherTest.AppSpecificError.type <: Throwable
 required: cats.data.EitherT[cats.effect.IO,Throwable,Int]
Note: _1 <: Throwable, but class EitherT is invariant in type A.
You may wish to define A as +A instead. (SLS 4.5)
      result <- if (flag) {
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-04 13:44:14

尝试显式指定类型参数。

代码语言:javascript
复制
EitherT.left[Int][IO, Throwable](AppSpecificError.pure[IO])

或使用类型归属

代码语言:javascript
复制
EitherT.left[Int]((AppSpecificError: Throwable).pure[IO])
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63247742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档