Avoiding implicit def ambiguity in Scala

后端 未结 6 1351
悲哀的现实
悲哀的现实 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:12

    The accepted solution (posted by Mitch Blevins) will never work: downcasting Int to String using asInstanceOf will always fail.

    One solution to your problem is to add a conversion from any String-convertible type to RichString (or rather, to StringOps as it is now named):

    implicit def stringLikeToRichString[T](x: T)(implicit conv: T => String) = new collection.immutable.StringOps(conv(x))
    

    Then define your conversion(s) to string as before:

    scala> implicit def intToString(i: Int) = String.valueOf(i)
    warning: there was one feature warning; re-run with -feature for details
    intToString: (i: Int)String
    
    scala> 100.toCharArray
    res0: Array[Char] = Array(1, 0, 0)
    
    scala> 100.reverse
    res1: String = 001
    
    scala> 100.length
    res2: Int = 3
    

提交回复
热议问题