首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >什么是“隐式”的Scala标识符?

什么是“隐式”的Scala标识符?
EN

Stack Overflow用户
提问于 2010-10-04 21:22:00
回答 2查看 65K关注 0票数 174

我在Scala示例中见过一个名为implicitly的函数。它是什么,它是如何使用的?

Example here

代码语言:javascript
复制
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

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

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3855595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档