[英]Why can method parameter F have the same name as type constructor F?
I was watching John De Goes "FP to the Max" video.我正在看 John De Goes “FP to the Max”视频。 In the code he does something like this to get the implicit object:
在代码中,他做了这样的事情来获取隐式对象:
object Program {
def apply[F[_]](implicit F: Program[F]): Program[F] = F
}
Does this imply that the variable name F (the first one in implicit F: Program[F]
) is actually a different F
?这是否意味着变量名 F (
implicit F: Program[F]
的第一个)实际上是一个不同的F
? It is very confusing.这很令人困惑。 Does he mean to do:
他的意思是:
object Program {
def apply[F[_]](implicit ev: Program[F]): Program[F] = ev
}
How does the compile know which F
he is referring to while returning the F
?如何编译知道
F
他是指在返回的F
? The type constructor or the variable in scope?类型构造函数还是作用域中的变量?
Indeed the function parameter T
is different from type parameter T
, for example事实上,函数参数
T
不同于类型参数T
,例如
def f[T](T: T): T = T
f(42) // res0: Int = 42
Compiler does not get confused because values exist in a different universe from types :编译器不会混淆,因为值与类型存在于不同的宇宙中:
...there exist two separate universes, the universe of types and the universe of values.
...存在两个独立的宇宙,类型的宇宙和值的宇宙。 In the universe of values, we have methods which take values as arguments in round parentheses (or occasionally curly braces).
在值的世界中,我们有一些方法将值作为圆括号(或偶尔花括号)中的参数。 In the universe of types, we have type constructors, which take types as arguments in square brackets.
在类型的世界中,我们有类型构造函数,它将类型作为方括号中的参数。
This convention is sometimes used when dealing with typeclasses.在处理类型类时有时会使用此约定。 It is meant to communicate that we want to simply return the typeclass instance resolved for
F
.它旨在传达我们想要简单地返回为
F
解析的类型类实例。 To avoid confusion you could use ev
approach you already suggested in question, or even为避免混淆,您可以使用您已经建议的
ev
方法,甚至
object Program {
def apply[F[_]: Program]: Program[F] = implicitly[Program[F]]
}
As a side-note, this trick with apply
method in companion object of typeclass allows us to avoid having to use implicitly
, for example, given作为旁注,这个在 typeclass 的伴生对象中使用
apply
方法的技巧允许我们避免implicitly
使用,例如,给定
trait Foo[T]
trait Bar[T]
trait Program[F[_]]
implicit val fooProgram: Program[Foo] = ???
implicit val barProgram: Program[Bar] = ???
object Program {
def apply[F[_]: Program]: Program[F] = implicitly
}
then we can write然后我们可以写
Program[Bar]
instead of代替
implicitly[Program[Bar]]
How does the compile know which
F
he is referring to while returning theF
?如何编译知道
F
他是指在返回的F
? The type constructor or the variable in scope?类型构造函数还是作用域中的变量?
The compiler knows that a method/function can only return a value.编译器知道一个方法/函数只能返回一个值。 So what follows the
=
has a type but is not a type.所以
=
后面的有一个类型但不是一个类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.