Implicit and implicit in Scala for implicit transformation and implicit parameters
Rules:
- Available only if marked implicit
- The implicit transformation being inserted must be a single identifier of the current scope or be associated with the source or target type of the implicit transformation
- Only one implicit definition can be inserted at a time
- Display priority. If it can pass type check directly, no implicit conversion will be performed
Implicit conversion
//The example implicitly converts a string to Int object Demo { case class R(width: Int, height: Int) implicit def stringToInt(s: String): Int = Integer.valueOf(s) def main(args: Array[String]): Unit = { println(R("4", 5)) } }
object Demo { //In the example, Int is implicitly converted to an R class case class R(width: Int, height: Int){ def + (that: R): R ={ R(this.width + that.width, this.height + that.width) } def + (that: Int): R = { R(that.width + that, that.height + that) } } implicit def intToR(i: Int): R = R(i, i) def main(args: Array[String]): Unit = { val r = R(2, 4) println(r + 1) println(1 + r) } }
object Demo { //Convert int to an implicit RMaker class case class R(width: Int, height: Int){ def + (that: R): R ={ R(this.width + that.width, this.height + that.width) } def + (that: Int): R = { R(that.width + that, that.height + that) } } implicit class RMaker(width: Int){ def x(height:Int) = R(width, height) } implicit def stringToInt(s: String): Int = Integer.valueOf(s) implicit def intToR(i: Int): R = R(i, i) def main(args: Array[String]): Unit = { val r = R(2, 4) println((1 + r) + (1 x 2)) } }
Implicit parameter
object Demo { case class SplitPrompt(s: String) case class R(width: Int, height: Int)(implicit splitPrompt: SplitPrompt){ override def toString: String = s"${width}${splitPrompt.s}${height}" } implicit val prompt: SplitPrompt = SplitPrompt("#") implicit class RMaker(width: Int){ def x(height:Int) = R(width, height) } implicit def stringToInt(s: String): Int = Integer.valueOf(s) implicit def intToR(i: Int): R = R(i, i) def main(args: Array[String]): Unit = { println(R(2, 4)) } }
Context is implicit
object Demo { case class SplitPrompt(s: String) case class R(width: Int, height: Int){ override def toString: String = s"${width}${implicitly[SplitPrompt].s}${height}" } implicit val prompt: SplitPrompt = SplitPrompt("#") implicit class RMaker(width: Int){ def x(height:Int) = R(width, height) } implicit def stringToInt(s: String): Int = Integer.valueOf(s) implicit def intToR(i: Int): R = R(i, i) def main(args: Array[String]): Unit = { println(R(2, 4)) } }