Functor Instance for Type Constructor with Two Parameters in Scala

前端 未结 2 1976
悲哀的现实
悲哀的现实 2021-01-03 00:48

I have a class Foo with two parameters, and I am trying to write a Functor instance for Foo with the first parameter fixed, as follows:

object S         


        
2条回答
  •  星月不相逢
    2021-01-03 01:01

    You're looking to partially apply a type-level constructor. Unfortunately, we can't directly do that. However, we can still do so indirectly using a little feature called Structural Types. In order to turn Foo from a two-argument type constructor into a one-argument type constructor, we'll define a type synonym inside of an anonymous, structural type.

    implicit def fooInstances[X]: Functor[({ type T[A] = Foo[X, A] })#T] =
      new Functor[({ type T[A] = Foo[X, A] })#T] {
        // ...
      }
    

    The braces {} in a type context define an anonymous type that we're exploiting to essentially create a lambda function at the type level. We define an anonymous type with an alias inside of it, then immediately evaluate that alias.

提交回复
热议问题