如果问题出在现有的隐含里面Predef
,你应该禁用Predef
进口这里所描述一样:Override Predef's implicit conversions
例如,让我们尝试做出新apply
功能String
。
scala> implicit def stringToFunction(s: String) = new {
| def apply(x1: Int) = ???
| }
stringToFunction: (s: String)AnyRef{def apply(x1: Int): Nothing}
scala> "123"(15)
<console>:13: error: type mismatch;
found : String("123")
required: ?{def apply: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method augmentString in object Predef of type (x: String)scala.collection.immutable.StringOps
and method stringToFunction of type (s: String)AnyRef{def apply(x1: Int): Nothing}
are possible conversion functions from String("123") to ?{def apply: ?}
"123"(15)
^
<console>:13: error: String("123") does not take parameters
"123"(15)
^
因此,我们应该从Predef
禁用augmentString
进口:
scala> import Predef.{augmentString => _, _}
import Predef.{augmentString=>_, _}
scala> "123"(15)
<console>:14: error: type mismatch;
found : String("123")
required: ?{def apply: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method wrapString in class LowPriorityImplicits of type (s: String)scala.collection.immutable.WrappedString
and method stringToFunction of type (s: String)AnyRef{def apply(x1: Int): Nothing}
are possible conversion functions from String("123") to ?{def apply: ?}
"123"(15)
^
<console>:14: error: String("123") does not take parameters
"123"(15)
^
让我们禁用wrapString
太多,那最终会实现我们想做的事:
scala> import Predef.{augmentString => _, wrapString => _, _}
import Predef.{augmentString=>_, wrapString=>_, _}
scala> "123"(15)
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:284)
at $anon$1.apply(<console>:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
... 31 elided
你可以做在编译器抱怨关于模糊转换后,您的类的隐式转换Foo
也是如此。
你有'隐式def f1(foo:Foo)'和'implicit def f2(foo:Foo)'。所以是的,现在还不清楚,即使创建的对象会应用()s具有不同的签名。为什么不把两个apply()放到一个隐式def中呢? – slouc
@slouc因为一个适用于Predef。 – Yaroslav