根据我的讲座,我是新手:
class Test [T: Comparing]
意味着它需要一个类型的隐式值Comparing[T]
,可以在该类的方法中使用。使用这种更高类型的符号
问题:这个表达def notation[F[_]: Sync] : F[Unit] = ???
是指什么?
根据我的讲座,我是新手:
class Test [T: Comparing]
意味着它需要一个类型的隐式值Comparing[T]
,可以在该类的方法中使用。使用这种更高类型的符号
问题:这个表达def notation[F[_]: Sync] : F[Unit] = ???
是指什么?
考虑具体类型和类型构造函数的区别
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
必须是类型类的成员Bar
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
必须是 typeclass 的成员Sync
才能调用notation
.