scala> :paste
// Entering paste mode (ctrl-D to finish)
class SpecialPerson(val name:String)
class Student(val name:String)
class Older(val name:String)
implicit def object2SpecialPerson(obj:Object):SpecialPerson = {
if(obj.getClass == classOf[Student]){val stu = obj.asInstanceOf[Student];new SpecialPerson(stu.name)}
else if(obj.getClass == classOf[Older]){val older = obj.asInstanceOf[Older];new SpecialPerson(older.name)}
else Nil
}
var ticketNumber = 0
def buySpecialTicket(p:SpecialPerson) = {
ticketNumber =1
"T-" ticketNumber
}
// Exiting paste mode, now interpreting.
<pastie>:15: warning: implicit conversion method object2SpecialPerson should be enabled
by making the implicit value scala.language.implicitConversions visible.
This can be achieved by adding the import clause 'import scala.language.implicitConversions'
or by setting the compiler option -language:implicitConversions.
See the Scaladoc for value scala.language.implicitConversions for a discussion
why the feature should be explicitly enabled.
implicit def object2SpecialPerson(obj:Object):SpecialPerson = {
^
defined class SpecialPerson
defined class Student
defined class Older
object2SpecialPerson: (obj: Object)SpecialPerson
ticketNumber: Int = 0
buySpecialTicket: (p: SpecialPerson)String
scala> val s = new Student("leo")
s: Student = Student@4d266391
scala> buySpecialTicket(s)
res0: String = T-1
scala> val o = new Older("Jike")
o: Older = Older@6afbe6a1
scala> buySpecialTicket(o)
res1: String = T-2
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Man(val name:String)
class Superman(val name:String){
def emitLaser = println("emit a laster!")
}
implicit def man2superman(man:Man):Superman = new Superman(man.name)
// Exiting paste mode, now interpreting.
defined class Man
defined class Superman
man2superman: (man: Man)Superman
scala> val leo = new Man("leo")
leo: Man = Man@618e7761
scala> leo.emitLaser
emit a laster!
scala> :paste
// Entering paste mode (ctrl-D to finish)
class SignPen{
def write(content:String) = println(content)
}
implicit val signPen = new SignPen
def signForExam(name:String)(implicit signPen:SignPen){
signPen.write(name " come to exam in time.")
}
// Exiting paste mode, now interpreting.
defined class SignPen
signPen: SignPen = SignPen@6c4d0224
signForExam: (name: String)(implicit signPen: SignPen)Unit
scala> signForExam("leo")(signPen)
leo come to exam in time.