简体   繁体   English

Scala中的隐式函数类型

[英]Implicit function types in Scala

Recently, I have become interested in implicit functions. 最近,我对隐式函数产生了兴趣。 In the documentation , we can see several examples of using this property, but I think I do not quite understand how it works. 文档中 ,我们可以看到使用此属性的几个示例,但是我想我不太了解它是如何工作的。

For example, we can read that implicit T0 => R is actually 例如,我们可以看到implicit T0 => R实际上是

trait ImplicitFunction1[-T0, R] extends Function1[T0, R] {
  override def apply(implicit x: T0): R
}

After writing the function below 写完下面的函数

val func = {implicit x: Int => 2*x}

I tried to use it in this way 我试图用这种方式

implicit val x: Int = 3
println(func)

But it doesn't seem to work (only the <function1> type is returned, it looks like apply hasn't been used at all). 但这似乎不起作用(仅返回<function1>类型,看起来根本没有使用apply )。 If I had a method for it, it would work fine 如果我有一个方法,它会很好地工作

def func(implicit x: Int) = 2*x

I'm not sure what I'm missing here. 我不确定我在这里缺少什么。

Implicit function types work in Dotty 隐式函数类型在Dotty中工作

https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html

https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html

In Scala 2 func has type Int => Int instead of absent implicit Int => Int (aka given Int => Int ). 在Scala 2中, func具有Int => Int类型,而不是缺少implicit Int => Int (又名given Int => Int )。

implicit x: Int => ??? is just a shorthand for x: Int => { implicit val _x: Int = x; ???} 只是x: Int => { implicit val _x: Int = x; ???}的简写x: Int => { implicit val _x: Int = x; ???} x: Int => { implicit val _x: Int = x; ???} . x: Int => { implicit val _x: Int = x; ???}

Out of all new implicit (aka given ) features in Dotty only by-name implicits were backported to Scala 2.13.0. 在Dotty中所有新的implicit (又名given )功能中,只有按名字命名的隐式被反向移植到Scala 2.13.0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM