sealed trait Foo[T] { def apply(list : Li-6ren">
gpt4 book ai didi

scala - Scala 标识符 "implicitly"是什么?

转载 作者:行者123 更新时间:2023-12-03 04:18:39 25 4
gpt4 key购买 nike

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

Example here :

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)意味着我们使用参数隐式调用。

另请参阅How to investigate objects/types/etc. from Scala REPL?Where does Scala look for implicits?

最佳答案

implicitly 在 Scala 2.8 中可用,并在 Predef 中定义。如:

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

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

来自 retronym's presentation 的简单示例:

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]
^

关于scala - Scala 标识符 "implicitly"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3855595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com