我正在尝试创建从任何类型(例如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中隐式定义歧义
发布评论