vendredi 26 juin 2015

Scala: How to make the return type of function generic and dependent on runtime arguments?

Say I have:

class Animal
class Bird extends Animal
class Dog extends Animal

How can I write a function that returns the runtime type (Bird or Dog) depending on the provided arguments.

I'm trying something like:

import scala.reflect.ClassTag
def createAnimal[T <: Animal : ClassTag](doesItBark: Boolean): T = {
    if (doesItBark) return new Dog()
    else return new Bird()
}


val azor = createAnimal(doesItBark = true) //azor's type should be Dog

Which doesn't work.

Is it possible to do something like this in Scala?





Aucun commentaire:

Enregistrer un commentaire