原创转载请注明出处:http://agilestyle.iteye.com/blog/2334855
这里看一个《Scala编程思想》中提供的一个多态示例,个人认为相当具有学习意义
Name.scala
package org.fool.scala.util
import scala.reflect.runtime.currentMirror
trait Name {
override def toString: String = Name.className(this)
}
object Name {
def className(o: Any) = currentMirror.reflect(o).symbol.toString.replace("$", " ").split(" ").last
}
Note:
这里先用Scala的反射机制重写toString方法获取类的实际名字
PolymorphismTest.scala
package org.fool.scala.polymorphism
import org.fool.scala.util.Name
class Element extends Name {
def interact(other: Element) = s"$this interact $other"
}
class Inert extends Element
class Wall extends Inert
trait Material {
def resilience: String
}
trait Wood extends Material {
def resilience = "Breakable"
}
trait Rock extends Material {
def resilience = "Hard"
}
class RockWall extends Wall with Rock
class WoodWall extends Wall with Wood
trait Skill
trait Fighting extends Skill {
def fight = "Fight!"
}
trait Digging extends Skill {
def dig = "Dig!"
}
trait Magic extends Skill {
def castSpell = "Spell!"
}
trait Flight extends Skill {
def fly = "Fly!"
}
class Character(var player: String = "None") extends Element
class Fairy extends Character with Magic
class Viking extends Character with Fighting
class Dwarf extends Character with Digging with Fighting
class Wizard extends Character with Magic
class Dragon extends Character with Magic with Flight
object PolymorphismTest extends App {
val d = new Dragon
d.player = "Puff"
// Dragon interact Wall
println(d.interact(new Wall))
def battle(fighter: Fighting) = s"$fighter, ${fighter.fight}"
// Viking, Fight!
println(battle(new Viking))
// Dwarf, Fight!
println(battle(new Dwarf))
// anon, Fight!
println(battle(new Fairy with Fighting))
def fly(flyer: Element with Flight, opponent: Element) =
s"$flyer, ${flyer.fly}, ${opponent.interact(flyer)}"
// Dragon, Fly!, Fairy interact Dragon
println(fly(d, new Fairy))
}
Note:
new Fairy with Fighting
该对象的类型是使用new表达式将现有的Fairy类与Fighting特征结合起来自己创建的,这样就创建了一个新类,而我们又立即创建了该类的一个实例。由于我们并没有给这个类起名字,因此Scala会帮我们起一个:$anon$1(anon是anonymous的缩写),而1是在Element的id碰到它时产生的。
Console Output

参考资料:
Scala编程思想
Scala多态性实践
本文通过具体的代码示例,展示了Scala语言中多态性的运用,包括如何通过特质和类实现多态行为,以及如何利用Scala的反射机制来重写toString方法获取类的实际名字。

303

被折叠的 条评论
为什么被折叠?



