避免在Scala中隐式定义歧义

编程入门 行业动态 更新时间:2024-10-24 08:29:52
本文介绍了避免在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中隐式定义歧义

本文发布于:2023-10-30 23:52:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:歧义   定义   隐式   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!