sk1007
sk1007

Reputation: 571

Sealed trait class conversion in Scala

How to get the base class from an extended class in scala. Actually, I am new in Scala and try to write some coding using sealed trait class.

For example, I have one sealed trail class and some case class extended to sealed trail class.

Eg:

sealed trait Person
case class Employer(name: String, id: Int, country: List[String]) extends Person
case class Employee(name: String, id: Int) extends Person

I am looking example of following type:

type example1 = RDD[(String, Int, Person)] => RDD[((String, Int), Employee)]

type example2 = RDD[(String, Int, List[Employer])] => RDD[((String, Int), List[Person])]

For example1: I am trying the following:

def getType1(data: RDD[(String, Int, Person)]) = {
   val res = data.map {
       x => {
         val emp = x._3.asInstanceOf[Employee]
         ((x._1, X._2), Employee(emp.name, emp.id)
         )
       }
   }
}

but how to do the reverse for type example2? An example will help me to understand my project, Please provide me the suggestion for it.

Upvotes: 0

Views: 1107

Answers (2)

Emiliano Martinez
Emiliano Martinez

Reputation: 4123

Something like that will work for you with both datatypes:

def getType1(data: RDD[(String, Int, Person)]) : RDD[((String, Int),Person)] = {
  data.map { case (s, i, person) => ((s, i), person)}
}

Upvotes: 0

puhlen
puhlen

Reputation: 8519

You should add the return type annotation to your method, it helps make it clear what type is being returned and gives you grater control over the type instead of leaving it up to the inferencer, since changing types is a big part of what you are trying to do it becomes even more important.

Your example1 has several problems. First, you aren't returning a value, so the return type is Unit which isn't what you want. Remove the val res = so that you return the result of the map. If you had added the return type, the compiler could catch this for you. If also doesn't handle the case where the Person from the RDD is not an Employee, you need to think about what to do in that case (filtering out those records or putting in a defautl value are both reasonable options but you might want something else.

In example 2 Because you want a more general type, you don't need to do any sort of checking or casting.

def example2(data: RDD[(String, Int, List[Employer])]): RDD[((String, Int), List[Person])] = data.map { x => ((x._1, x._2), x._3)}

Employer is a subtype of person, and List is covariant, so List[Employer] is a subtype of List[Person] so you can use a List[Employer] anywhere a List[Person] is required.

Upvotes: 1

Related Questions