Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type alias optimization skipping implicit conversion in Scala?

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?

like image 255
Gertjan Assies Avatar asked May 23 '26 19:05

Gertjan Assies


1 Answers

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.

like image 170
0__ Avatar answered May 26 '26 15:05

0__



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!