173 Scala Implicit Conversion and Implicit Parameters

Keywords: Scala Java

Implicit transformation and implicit parameters are two very powerful functions in Scala. With implicit transformation and implicit parameters, you can provide elegant class libraries and hide boring details from the users of class libraries.

Implicit enhancements of class methods enrich the functions of existing class libraries.

Implicit conversion functions refer to those functions declared with implicit keywords with a single parameter.

Example:

package cn.itcast.impli

import java.io.File
import scala.io.Source


//Implicit Enhancement of File Classes
class RichFile(val from: File) {
  def read = Source.fromFile(from.getPath).mkString
}

object RichFile {
  //Implicit Conversion Method
  implicit def file2RichFile(from: File) = new RichFile(from)

}

object MainApp{
  def main(args: Array[String]): Unit = {
    //Import implicit transformation
    import RichFile._
    //import RichFile.file2RichFile
    println(new File("c://words.txt").read)

  }
}

package cn.itcast.scala

import java.awt.GridLayout

 
object ImplicitContext{
  //implicit def girl2Ordered(g : Girl) = new Ordered[Girl]{
  //  override def compare(that: Girl): Int = if (g.faceValue > that.faceValue) 1 else -1
  //}

  implicit object OrderingGirl extends Ordering[Girl]{
    override def compare(x: Girl, y: Girl): Int = if (x.faceValue > y.faceValue) 1 else -1
  }
}

class Girl(var name: String, var faceValue: Double){
  override def toString: String = s"name : $name, faveValue : $faceValue"
}

//class MissRight[T <% Ordered[T]](f: T, s: T){
//  def choose() = if(f > s) f else s
//}
//class MissRight[T](f: T, s: T){
//  def choose()(implicit ord: T => Ordered[T]) = if (f > s) f else s
//}

class MissRight[T: Ordering](val f: T, val s: T){
  def choose()(implicit ord: Ordering[T]) = if(ord.gt(f, s)) f else s
}

object MissRight {
  def main(args: Array[String]) {
    import ImplicitContext.OrderingGirl
    val g1 = new Girl("yuihatano", 99)
    val g2 = new Girl("jzmb", 98)
    val mr = new MissRight(g1, g2)
    val result = mr.choose()
    println(result)
  }
}

Posted by Braveheartt on Sun, 06 Oct 2019 09:34:08 -0700