【问题标题】:Difference between [A: C] and [A[_]: C] context bounds[A: C] 和 [A[_]: C] 上下文边界之间的区别
【发布时间】:2020-10-03 01:58:40
【问题描述】:

根据我的讲座,我是新手: class Test [T: Comparing] 意味着它需要一个 Comparing[T] 类型的隐式值,可以在该类的方法中使用。 使用这种更高种类的类型表示法

问题:这个表达式def notation[F[_]: Sync] : F[Unit] = ???指的是什么?

【问题讨论】:

标签: scala implicit higher-kinded-types type-constructor context-bound


【解决方案1】:

考虑具体类型和类型构造函数

的区别
Int         // concrete type
List[Int]   // concrete type
List        // type constructor

我们使用符号F[_]表示类型构造函数的形状

trait Foo[T]            // Foo takes any type
trait Bar[F[_]]         // Bar takes any type constructor

new Foo[Int] {}         // ok
new Foo[List[Int]] {}   // ok
new Foo[List] {}        // error

new Bar[Int] {}         // error
new Bar[List[Int]] {}   // error 
new Bar[List] {}        // ok

我们可以将类型参数子句[F[_]: Bar]理解为含义

  • 方法需要 Bar[F] 类型的隐式值,其中 F 是类型构造函数
  • 类型构造函数F 必须是类型类Barmember
trait Bar[F[_]]

// make type constructor Foo a member of typeclass Bar
implicit val barOfFoo: Bar[Foo] = new Bar[Foo] { println("woohoo") }

def g[F[_]: Bar] = implicitly[Bar[F]]

g[Foo]        // ok
g[Int]        // error - type parameter is of incorrect shape
g[Foo[Int]]   // error - type parameter is of incorrect shape
g[List]       // error - type parameter is of correct shape but not a member of Bar

将上述概念应用于def notation[F[_]: Sync],我们看到类型构造函数F 必须是类型类Sync 的成员才能调用notation

【讨论】:

  • 有趣 - g[Foo[Int]] 没有被 intellij 的 scala 插件捕获(至少在最新的 EAP 版本中)。
  • @mtk 这似乎是编辑器类型感知突出显示的错误。 Metals 正确突出显示它。
猜你喜欢
  • 2023-03-15
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多