Reputation: 2811
I have a function that gets a string with name of model and returning an instance of that case class, but im wondering what is the correct way to use dynamic return type here in this function?
case class Person(fname: String, lname: String)
case class Animal(type: String, weight: Double)
def getInstanceOf(model: String): ??? = model match {
case "person" => Person("jack", "robinson")
case "animal" => Animal("lion", 190.0)
}
thanks!
Upvotes: 0
Views: 1420
Reputation: 608
It may help to have a bit more context of what the end goal is here to suggest a solution.
If your models all conform to a particular classification and you don't need to know exactly what instance they are then the abstract class
(or trait
) suggestion above should work.
EDIT: my original answer included this snippet:
You could also make the return type generic and put a type boundary on it in this scenario, such as:
def getInstanceOf[T <: Living](model: String): T = ...
But as pointed out below this allows the caller to specify what type they expect which may counteract what is contained in the model
argument
If you only returned one of two possible types but needed the exact type then maybe an Either[T1, T2]
would be appropriate here (http://www.scala-lang.org/api/current/scala/util/Either.html) such as:
def getInstanceOf(model: String): Either[Person, Animal] = ...
But again I think it would be easier to answer if the end goal was explained a bit
Upvotes: 6
Reputation: 215137
Maybe you can define an abstract class and extends both classes from it, and then you can specify the abstract class as the return type:
abstract class Living
case class Person(fname: String, lname: String) extends Living
case class Animal(Type: String, weight: Double) extends Living
def getInstanceOf(model: String): Living = model match {
case "person" => Person("jack", "robinson")
case "animal" => Animal("lion", 190.0)
}
// getInstanceOf: (model: String)Living
Upvotes: 6