我需要根據傳遞的泛型選擇一個對象實現。這裏是我想要的一個小例子如何在運行時選擇一個對象 - Scala
import scala.reflect.runtime.universe.{TypeTag,typeOf}
trait Animal27
{
val name: String
val sound: String
}
case class Tiger27(name:String, sound: String) extends Animal27
object Tiger27
{
def AbilityEvolve(tiger27 : Tiger27) : String =
{
tiger27.name + " is a tigher and she has increased attack"
}
}
case class Cheetah27(name:String,sound:String) extends Animal27
object Cheetah27
{
def AbilityEvolve(cheetah27: Cheetah27): String =
{
cheetah27.name + "is a cheethah and he has increased speed"
}
}
class World[A: TypeTag] {
def getMyObject =
{
if (typeOf[A] =:= typeOf[Cheetah27])
Cheetah27
else
Tiger27
}
def Evolve : String =
{
getMyObject.AbilityEvolve + " hence evolved" // how do i perform
//getMyObject.AbilityEvolve
}
}
object App27 extends App{
val world = new World[Cheetah27]
println(world.Evolve)
}
我可以知道如何動態選擇基於所用通用對象。那麼如何確保getMyObject.AbilityEvolve能夠調用相應對象的方法?
感謝
如果我希望foo()返回相應的對象/修改的對象,這看起來如何?謝謝。 – BigDataScholar