implicit conversion and implicit parameters

package p20140709.types

class PreferredDrink(val drkname:String)

package p20140709.types

class PreferredPrompt(val preference:String)

package p20140709.pres

import p20140709.types.{PreferredPrompt, PreferredDrink}

object JoesPrefss {
   implicit val pmpt=new PreferredPrompt("Yes,man% ")
   implicit val drk=new PreferredDrink("Coca");

   //implicit val prompt=new PreferrePrompt("Yes,dude % ")
   //following codes won't work
   //val prompt=new PreferrePrompt("Yes,dude % ")
 }

package p20140709

//import JoesPrefs.prompt

import pres._
import pres.JoesPrefss.{pmpt, drk}
import types.{PreferredPrompt => PP, PreferredDrink => PD}

/**
 * Created by Administrator on 14-7-9.
 */
object Main20140709 extends App {
  /*val bobsPrompt=new PreferrePrompt("ssss> ")
  Greeter.greet("Hello")(bobsPrompt)*/

  Greeter.greet("Jop")

  implicit object StringMonoid extends Monoid[String] {
    def add(x: String, y: String): String = x concat y

    def unit: String = ""
  }

  implicit object IntMonoid extends Monoid[Int] {
    def add(x: Int, y: Int): Int = x + y

    def unit: Int = 0
  }

  def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
    if (xs.isEmpty) m.unit
    else m.add(xs.head, sum(xs.tail))

  println("List(1,2,3,4) result: " + sum(List(1, 2, 3, 4)))
  println("List(\"a\",\"b\",\"c\",\"d\",\"e\") result: " + sum(List("a", "b", "c", "d", "e")))
}

//implicit parameters usually have "rare" or "special" enough types that accidental matches are unlikely.
//types PreferredPrompt and PreferredDrink were defined solely to serve as implicit parameter types.
//as a result, it is unlikely that implicit variables of these types will be in scope if they aren't intended
//to be used as implicit parameters to Greeter.greet

object Greeter {


  //implicit match did only by their type(Class Type in this case)
  def greet(name: String)(implicit prompt: PP, drik: PD) {
    println("Weilcome. " + name + ". The system is ready.")
    print(" But while you work, ")
    println("why not enjoy a cup of " + drik.drkname + "?")
    println(prompt.preference)
  }
}

abstract class SemiGroup[A] {
  def add(x: A, y: A): A
}

abstract class Monoid[A] extends SemiGroup[A] {
  def unit: A
}


/*object JoesPrefs {
  //implicit val pmpt=new PreferrePrompt("Yes,man% ")

  implicit val prompt=new PreferrePrompt("Yes,dude % ")
  //following codes won't work
  //val prompt=new PreferrePrompt("Yes,dude % ")
}*/


你可能感兴趣的:(scala,conversion,Implicit,currying)