假设有以下情况:
scala> trait Foo { def get: String = "get" }
defined trait Foo我实现了它并做了一个隐式的:
scala> case class FooImpl(x: String) extends Foo {
| override def get = s"got $x"
| }
defined class FooImpl
scala> implicit val fooImpl = FooImpl("yo")
fooImpl: FooImpl = FooImpl(yo)最后,我尝试编写一个隐式解析Foo的方法,在隐式解析的类上返回get。
scala> def f[A: Foo](x: A) = x.get
<console>:11: error: Foo does not take type parameters
def f[A: Foo](x: A) = x.get
^
<console>:11: error: value get is not a member of type parameter A
def f[A: Foo](x: A) = x.get
^但是我得到了上面的错误。
所以我用implicit关键字重写了它:
scala> def f(implicit x: Foo): String = x.get
f: (implicit x: Foo)String
scala> f
res0: String = got yo是否可以重写此示例,使其不显式指定implicit关键字?
注意--我可能把这个符号和Using a Context bound of a Type Parameter部分下的TypeTag混淆了。
发布于 2015-04-19 22:34:55
你使用了错误的语法,你想要的是一个上限:
scala> def f[A <: Foo](x: A) = x.get
f: [A <: Foo](x: A)String这里您说A是Foo的子类型,这告诉编译器A确实有一个名为get的方法。
你正在使用的语法(:)意味着有一个从A到Foo[A]的隐式转换,问题是Foo没有接受类型参数,你也可以把它签入到REPL中,在那里列语法被转换为隐式参数:
scala> trait Foo2[T]
defined trait Foo2
scala> def g[T: Foo2](x: Int): Int = x
g: [T](x: Int)(implicit evidence$1: Foo2[T])Inthttps://stackoverflow.com/questions/29731128
复制相似问题