1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Human(var name:String){ def sayHello(): Unit ={ println(s"hello, I'm $name") } def makeFriends(p:Human)={ sayHello() p.sayHello() } }
class Student(name:String) extends Human(name)
class Cat(var name:String){ def sayHello(): Unit ={ println(s"I'm a cat name is $name") } }
class Party [ T<% Human](p1:T,p2:T){ p1.makeFriends(p2) }
object ImplicitDemo05 { def main(args: Array[String]): Unit = { val human1 = new Human("小明") val human2 = new Human("小红") val party1 = new Party[Human](human1,human2)
val s1 = new Student("小学生") val s2 = new Student("中学生") val party2 = new Party[Student](s1,s2)
val c1 = new Cat("加菲猫") val c2 = new Cat("小花猫")
implicit def cat2Human(cat:Cat):Human ={ new Human(cat.name) } val party3 = new Party[Cat](c1,c2)
} }
|