Home > Software engineering >  Scala : Add an implicit method to transform case class to another case class in alias object?
Scala : Add an implicit method to transform case class to another case class in alias object?

Time:11-10

I am new to Scala and I have a case class like this:

case class Student(
 name: String,
 age: Option[Int] = None,
 id: String
)

and another case class like this:

case class Member(
 id: String,
 `type`: String,
 name: String
)

I want to create a helper implicit in such a way that:

case class Member(
 id: String,
 `type`: String,
 name: String
)

object Member {
  implicit def toStudent(member:Member):Student = Student(member.name,None,member.id)
}

and then call the method like this:

val newMember = Member("abc","Student","John")
val student = newMember.toStudent

or something fancy like that. Would this be possible in Scala as I see a lot of fancy syntax similar to this at a lot of places?

CodePudding user response:

In Scala 3 you can use extensions methods:

// ...

extension (member: Member)
  def toStudent: Student = Student(member.name, None, member.id)

val newMember = Member("abc", "Student", "John")
val student = newMember.toStudent

For Scala 2 you can define explicit conversion:

import scala.language.implicitConversions
object Member {
  implicit def toStudent(member: Member): Student =
    Student(member.name, None, member.id)
}

val newMember = Member("abc", "Student", "John")
val student = newMember: Student

Or using implicit class decorator:

implicit class MemberDecorator(val member: Member) extends AnyVal {
  def toStudent(): Student = Student(member.name, None, member.id)
}

val newMember = Member("abc", "Student", "John")
val student = newMember.toStudent()
  • Related