简体   繁体   English

scala 中的 Kleisli 推理与猫

[英]Kleisli Inference in scala with cats

Quick question快速提问

With

trait SubEnv1
trait SubEnv2

While i understand (I think) why the following code would work:虽然我理解(我认为)为什么以下代码会起作用:

    def logic  =
        for {
            s1  <- Kleisli{(e:SubEnv1) => Option("hello")}
            s1  <- Kleisli{(e:Any) => Option("hello2")}
        } yield (s1)
//cats.data.Kleisli[Option,SubEnv1,String]

I am confused as to why the following does not work:我对以下为什么不起作用感到困惑:

def logic  =
    for {
        s1  <- Kleisli{(e:SubEnv1) => Option("hello")}
        s1  <- Kleisli{(e:Nothing) => Option("hello2")}
    } yield (s1)

//type mismatch;
//found   : Nothing => Option[String]
//required: A => Option[String]

In fact i do not understand the error.事实上我不明白这个错误。

The type of flatMap is flatMap 的类型是

def flatMap[C, AA <: A](f: B => Kleisli[F, AA, C])(implicit F: FlatMap[F]): Kleisli[F, AA, C]

So we have AA <: A所以我们有 AA <: A

  1. The first work because of contravariance i think.我认为第一个工作是因为逆变。 Where AA => Option[C] is expected we can pass can take Any => Option[C] AA => Option[C]预计我们可以通过可以采取Any => Option[C]

  2. The second is rather strange given the requirement AA <: A and鉴于要求AA <: A

implicitly[Nothing <:< SubEnv1]
// Nothing <:< SubEnv1 = generalized constraint

So what does //required: A => Option[String] that it requires a type but Nothing?那么//required: A => Option[String]它需要一个类型但什么都没有呢?

I believe you are simply hitting this bug: Nothing does not conform to arbitrary type parameter #9453我相信您只是遇到了这个错误: Nothing does not conform to any type parameter #9453

Proof:证明:

Kleisli { (e: SubEnv1) => Option("hello") }.flatMap[String, Nothing] { s1 =>  
    Kleisli[Option, Nothing, String] { (e: Nothing) => Option("boo") }
}
res34: Kleisli[Option, Nothing, String] = Kleisli(cats.data.Kleisli$$$Lambda$2297/0x0000000800c08840@1385e9e3)

(typechecks correctly) (类型检查正确)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM