174

implicitly在 Scala 示例中看到了一个名为 used 的函数。它是什么,它是如何使用的?

这里的例子

scala> sealed trait Foo[T] { def apply(list : List[T]) : Unit }; object Foo {
     |                         implicit def stringImpl = new Foo[String] {
     |                             def apply(list : List[String]) = println("String")
     |                         }
     |                         implicit def intImpl = new Foo[Int] {
     |                             def apply(list : List[Int]) =  println("Int")
     |                         }
     |                     } ; def foo[A : Foo](x : List[A]) = implicitly[Foo[A]].apply(x)
defined trait Foo
defined module Foo
foo: [A](x: List[A])(implicit evidence$1: Foo[A])Unit

scala> foo(1)
<console>:8: error: type mismatch;
 found   : Int(1)
 required: List[?]
       foo(1)
           ^
scala> foo(List(1,2,3))
Int
scala> foo(List("a","b","c"))
String
scala> foo(List(1.0))
<console>:8: error: could not find implicit value for evidence parameter of type
 Foo[Double]
       foo(List(1.0))
          ^

请注意,我们必须编写implicitly[Foo[A]].apply(x),因为编译器认为这 implicitly[Foo[A]](x)意味着我们implicitly使用参数调用。

另请参阅如何调查对象/类型/等。来自 Scala REPL?Scala 在哪里寻找隐式

4

4 回答 4

221

implicitly在 Scala 2.8 中可用,在Predef中定义为:

def implicitly[T](implicit e: T): T = e

它通常用于检查类型的隐式T是否可用,如果是,则返回它。

来自retronym的演示的简单示例:

scala> implicit val a = "test" // define an implicit value of type String
a: java.lang.String = test
scala> val b = implicitly[String] // search for an implicit value of type String and assign it to b
b: String = test
scala> val c = implicitly[Int] // search for an implicit value of type Int and assign it to c
<console>:6: error: could not find implicit value for parameter e: Int
       val c = implicitly[Int]
                         ^
于 2010-10-04T13:22:34.073 回答
210

以下是使用令人愉快的简单方法的几个原因implicitly

了解/排除隐式视图的问题

隐式视图可以在选择的前缀时触发(例如,考虑the.prefix.selection(args)不包含selection适用于的成员args(即使在尝试args使用隐式视图进行转换后)。在这种情况下,编译器会查找本地定义的隐式成员在当前或封闭范围内,继承或导入,它们是从该类型the.prefix到具有已selection定义类型的函数或等效的隐式方法。

scala> 1.min(2) // Int doesn't have min defined, where did that come from?                                   
res21: Int = 1

scala> implicitly[Int => { def min(i: Int): Any }]
res22: (Int) => AnyRef{def min(i: Int): Any} = <function1>

scala> res22(1) // 
res23: AnyRef{def min(i: Int): Int} = 1

scala> .getClass
res24: java.lang.Class[_] = class scala.runtime.RichInt

当表达式不符合预期类型时,也可以触发隐式视图,如下所示:

scala> 1: scala.runtime.RichInt
res25: scala.runtime.RichInt = 1

编译器在这里寻找这个函数:

scala> implicitly[Int => scala.runtime.RichInt]
res26: (Int) => scala.runtime.RichInt = <function1>

访问由上下文绑定引入的隐式参数

隐式参数可以说是 Scala 比隐式视图更重要的特性。它们支持类型类模式。标准库在几个地方使用了它——看看scala.Ordering它是如何使用的SeqLike#sorted。隐式参数也用于传递数组清单和CanBuildFrom实例。

Scala 2.8 允许隐式参数的简写语法,称为上下文边界。简而言之,具有类型参数的方法A需要类型的隐式参数M[A]

def foo[A](implicit ma: M[A])

可以改写为:

def foo[A: M]

但是传递隐式参数但不命名它有什么意义呢?这在实现该方法时有何用处foo

通常,不需要直接引用隐式参数,它将作为隐式参数通过隧道传递给另一个被调用的方法。如果需要,您仍然可以使用 Context Bound 保留简洁的方法签名,并调用implicitly以实现该值:

def foo[A: M] = {
   val ma = implicitly[M[A]]
}

显式传递隐式参数的子集

假设您正在使用基于类型类的方法调用一个漂亮地打印一个人的方法:

trait Show[T] { def show(t: T): String }
object Show {
  implicit def IntShow: Show[Int] = new Show[Int] { def show(i: Int) = i.toString }
  implicit def StringShow: Show[String] = new Show[String] { def show(s: String) = s }

  def ShoutyStringShow: Show[String] = new Show[String] { def show(s: String) = s.toUpperCase }
}

case class Person(name: String, age: Int)
object Person {
  implicit def PersonShow(implicit si: Show[Int], ss: Show[String]): Show[Person] = new Show[Person] {
    def show(p: Person) = "Person(name=" + ss.show(p.name) + ", age=" + si.show(p.age) + ")"
  }
}

val p = Person("bob", 25)
implicitly[Show[Person]].show(p)

如果我们想改变名字的输出方式怎么办?我们可以显式调用PersonShow,显式传递一个替代Show[String],但我们希望编译器传递Show[Int].

Person.PersonShow(si = implicitly, ss = Show.ShoutyStringShow).show(p)
于 2010-10-04T22:05:44.547 回答
3

启动 Scala 3implicitly已替换为改进summon的,其优点是能够返回比要求的更精确的类型

summon方法隐式对应于Scala 2中。它与Shapeless中的方法完全相同。summon(或)和之间的区别在于implicitly,召唤可以返回比所要求的类型更精确的类型。

例如给定以下类型

trait F[In]:
  type Out
  def f(v: Int): Out

given F[Int] with 
  type Out = String
  def f(v: Int): String = v.toString

implicitly方法将调用一个带有已擦除类型成员的术语Out

scala> implicitly[F[Int]]
val res5: F[Int] = given_F_Int$@7d0e5fbb

scala> implicitly[res5.Out =:= String]
1 |implicitly[res5.Out =:= String]
  |                               ^
  |                               Cannot prove that res5.Out =:= String.

scala> val x: res5.Out = ""
1 |val x: res5.Out = ""
  |                  ^^
  |                  Found:    ("" : String)
  |                  Required: res5.Out

为了恢复类型成员,我们必须显式引用它,这违背了使用类型成员而不是类型参数的目的

scala> implicitly[F[Int] { type Out = String }]
val res6: F[Int]{Out = String} = given_F_Int$@7d0e5fbb

scala> implicitly[res6.Out =:= String]
val res7: res6.Out =:= String = generalized constraint

然而summon定义为

def summon[T](using inline x: T): x.type = x

没有这个问题

scala> summon[F[Int]]
val res8: given_F_Int.type = given_F_Int$@7d0e5fbb

scala> summon[res8.Out =:= String]
val res9: String =:= String = generalized constraint

scala> val x: res8.Out = ""
val x: res8.Out = ""

我们看到 type membertype Out = String没有被删除,即使我们只要求F[Int]而不是F[Int] { type Out = String }当链接依赖类型的函数时,这可以证明特别相关:

隐式调用的类型没有Out类型成员。出于这个原因,我们应该在使用依赖类型函数时隐式地避免。

于 2021-04-17T21:23:30.343 回答
-4

“教你钓鱼”的答案是使用Scaladoc nightlies中当前可用的字母成员索引。包/类窗格顶部的字母(和#, 表示非字母名称)是指向以该字母开头的成员名称索引的链接(跨所有类)。例如,如果您选择I,您会在 中找到implicitly出现一次的条目,Predef您可以从那里的链接访问该条目。

于 2010-10-04T13:50:19.063 回答