Avoiding implicit def ambiguity in Scala

后端 未结 6 1379
悲哀的现实
悲哀的现实 2021-01-07 23:27

I am trying to create an implicit conversion from any type (say, Int) to a String...

An implicit conversion to String means RichString methods (like reverse) are not

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-08 00:03

    I don't have a solution, but will comment that the reason RichString methods are not available after your intToString implicit is that Scala does not chain implicit calls (see 21.2 "Rules for implicits" in Programming in Scala).

    If you introduce an intermediate String, Scala will make the implict converstion to a RichString (that implicit is defined in Predef.scala).

    E.g.,

    $ scala
    Welcome to Scala version 2.7.5.final [...].
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> implicit def intToString(i: Int) = String.valueOf(i)
    intToString: (Int)java.lang.String
    
    scala> val i = 100
    i: Int = 100
    
    scala> val s: String = i
    s: String = 100
    
    scala> s.reverse
    res1: scala.runtime.RichString = 001
    

提交回复
热议问题