`

Scala Polymorphism

 
阅读更多

原创转载请注明出处: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编程思想

 

 

 

  • 大小: 15.4 KB
分享到:
评论

相关推荐

    A.Beginner's.Guide.to.Scala

    Scala中的面向对象编程部分,采用了传统面向对象设计中的关键概念,如类(class)、对象(object)、继承(inheritance)、多态(polymorphism)和封装(encapsulation)。然而,Scala的面向对象编程与传统的OOP语言...

    [Pragmatic Bookshelf] Functional Programming Patterns in Scala and Clojure

    OOP强调封装(Encapsulation)、继承(Inheritance)、多态(Polymorphism)等核心概念。 - **过渡挑战**:对于长期从事OOP开发的程序员而言,转向FP会面临诸多挑战。这不仅涉及编程思维模式的根本转变,还需要学习...

    Scala入门教程详解

    3. 多态/动态绑定(Polymorphism/dynamic binding) 4. 所有预定义类型都是对象(All predefined types are objects) 5. 所有操作都是通过发送消息给对象来实现的(All operations are performed by sending ...

Global site tag (gtag.js) - Google Analytics