关于路径依赖类型的上下文边界和隐式参数列表的行为 [英] Behaviour of context bounds and implicit parameter lists with regards to path dependent types

查看:36
本文介绍了关于路径依赖类型的上下文边界和隐式参数列表的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为上下文边界和隐式参数列表的行为完全相同,但显然不是.

I always thought that context bounds and implicit parameter lists behaved exactly the same, but apparently not.

在下面的示例中,我希望 summon1[Int]summon2[Int] 返回相同的类型,但它们没有.我希望 summon2[Int] 返回一个依赖于路径的类型,但它给了我一个类型投影.为什么?

In the example below, I expect summon1[Int] and summon2[Int] to return the same type, but they don't. I expected summon2[Int] to return a path dependent type, but instead it gives me a type projection. Why?

Welcome to the Ammonite Repl 2.2.0 (Scala 2.13.3 Java 11.0.2)
@ trait Foo[A] {
    type B
    def value: B
  }
defined trait Foo

@ implicit def fooInt = new Foo[Int] {
      override type B = String
      override def value = "Hey!"
    }
defined function fooInt

@ implicit def fooString = new Foo[String] {
      override type B = Boolean
      override def value = true
    }
defined function fooString

@ def summon1[T](implicit f: Foo[T]) = f.value
defined function summon1

@ def summon2[T: Foo] = implicitly[Foo[T]].value
defined function summon2

@ summon1[Int]
res5: String = "Hey!"

@ summon2[Int]
res6: Foo[Int]#B = "Hey!"

@

推荐答案

主要不在于上下文绑定与隐式参数的区别(应该没有任何区别 (*)),问题是 implicitly 可以打破隐式发现的类型

The thing is primarily not in the difference of context bound vs. implicit parameter (there shouldn't be any difference (*)), the thing is that implicitly can break type of implicit found

https://typelevel.org/blog/2014/01/18/implicitly_existential.html

如果您使用自定义实现器修复 summon2,这将按预期工作

If you fix summon2 using custom materializer this will work as expected

def materializeFoo[T](implicit f: Foo[T]): Foo[T] { type B = f.B } = f

def summon2[T: Foo] = materializeFoo[T].value

summon2[Int]
// val res: String = Hey!

有趣的是 shapeless.the 没有帮助

def summon2[T: Foo] = the[Foo[T]].value

summon2[Int]
// val res: Foo[Int]#B = Hey!

同样在 Scala 2.13 中,您可以使用更通用的实体化形式(并非特定于 Foo)返回单例类型(例如 在 Scala 中完成 3)

Also in Scala 2.13 you can use more general form of materializer (not specific for Foo) returning singleton type (like it's done in Scala 3)

def materialize[A](implicit f: A): f.type = f

def summon2[T: Foo] = materialize[Foo[T]].value

val y = summon2[Int]
// val res: String = Hey!


(*) 嗯,有一个区别,如果不引入参数名f,就不能在返回类型中显式引用类型fB.如果你没有明确指定返回类型,我们可以看到这样的类型 fB 由于缺少 stable 前缀 f(另见 Aux-pattern 用法编译时没有推断出适当的类型).


(*) Well, there is a difference that if you don't introduce parameter name f you can't refer to the type f.B explicitly in the return type. And if you don't specify return type explicitly, as we can see such type f.B can't be inferred because of the lack of a stable prefix f (see also Aux-pattern usage compiles without inferring an appropriate type).

这篇关于关于路径依赖类型的上下文边界和隐式参数列表的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆