What is the ? type?

大城市里の小女人 提交于 2019-12-05 06:16:58

It is special syntax for so-called type lambdas that is added by the kind projector plugin.

Either[A, ?]

is a shortcut for

({type L[X] = Either[A, X]})#L

The whole code desugars to

import cats.Monad

object EitherMonad {
  implicit def instance[A]: Monad[({type L[X] = Either[A, X]})#L] = new Monad[({type L[X] = Either[A, X]})#L] {
    def pure[B](b: B): Either[A, B] = Right(b)

    def flatMap[B, C](fa: Either[A, B])(f: B => Either[A, C]): Either[A, C] =
      fa.right.flatMap(f)
  }
}

Type lambdas look frightening, but they are essentially a very simple concept. You have a thing that takes two type parameters, like Either[A, B]. You want to provide a monad instance for Either, but trait Monad[F[_]] takes only one type parameter. But in principle that's OK, since your monad instance is only concerned with the second (the "right") type argument anyway. A type lambda is just a way to "fix" the first type argument so you have the right shape.

If you would do the same thing at value level, you wouldn't even think about it twice. You got a function of two arguments

val f: (Int, Int) => Int = ...

And something you want to pass f to, which only takes 1 argument

def foo(x: Int => Int) = ...

The only way to make things fit is to fix one of the arguments

foo(x => f(1, x))

And that's exactly what a type lambda does at type level.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!