I have the following code:
type RString = String
implicit def stringToRString(s:String):RString = s.reverse
val s = "The Force Awakens"
val r:RString = s
println(r)
I kind of expected r to be the reverse of s but it is equal to s.
Is this the scala compiler taking a shortcut as RString is an alias of String so the implicit conversion is never called?
A type alias does not introduce a new type, it's an alias. You can replace left and right hand side. Thus r: RString is the same as r: String, and therefore no conversion is required.
You would need something like this:
object RString {
// allow RString to be used as a String
implicit def toString(r: RString): String = r.toString
}
implicit class RString(val peer: String) extends AnyVal {
override def toString = peer.reverse
}
val s = "The Force Awakens"
val r: RString = s // "snekawA ecroF ehT"
That is, RString is a new type, a value class that reverses the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With