避免在Scala中隐式定义歧义 [英] Avoiding implicit def ambiguity in Scala
问题描述
我正在尝试创建从任何类型(例如Int)到字符串的隐式转换...
I am trying to create an implicit conversion from any type (say, Int) to a String...
隐式转换为String意味着RichString方法(如反向)不可用.
An implicit conversion to String means RichString methods (like reverse) are not available.
implicit def intToString(i: Int) = String.valueOf(i)
100.toCharArray // => Array[Char] = Array(1, 0, 0)
100.reverse // => error: value reverse is not a member of Int
100.length // => 3
对RichString的隐式转换意味着String方法(如toCharArray)不可用
An implicit conversion to RichString means String methods (like toCharArray) are not available
implicit def intToRichString(i: Int) = new RichString(String.valueOf(i))
100.reverse // => "001"
100.toCharArray // => error: value toCharArray is not a member of Int
100.length // => 3
同时使用两个隐式转换意味着重复的方法(如长度)是不明确的.
Using both implicit conversions means duplicated methods (like length) are ambiguous.
implicit def intToString(i: Int) = String.valueOf(i)
implicit def intToRichString(i: Int) = new RichString(String.valueOf(i))
100.toCharArray // => Array[Char] = Array(1, 0, 0)
100.reverse // => "001"
100.length // => both method intToString in object $iw of type
// (Int)java.lang.String and method intToRichString in object
// $iw of type (Int)scala.runtime.RichString are possible
// conversion functions from Int to ?{val length: ?}
那么,是否可以隐式转换为String并仍然支持所有String和RichString方法?
So, is it possible to implicitly convert to String and still support all String and RichString methods?
推荐答案
要么建立一个庞大的代理类,要么吸纳它,并要求客户端消除歧义:
Either make a huge proxy class, or suck it up and require the client to disambiguate it:
100.asInstanceOf [String] .length
100.asInstanceOf[String].length
这篇关于避免在Scala中隐式定义歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!