简体   繁体   中英

How to patten match on just the class, not the class attributes in Scala?

I have some classes which sometimes have many many attributes, the classes are very large, so I don't want to turn the class into a case class.

However, I still want to be able to do a pattern match on the class type.

What I have been doing is the following:

object CourseSemester {
  implicit val courseSemesterCase = (entity: CourseSemester) 
                     => { CourseSemesterCase(entity) }
  case class CourseSemesterCase(entity: CourseSemester)
}

import CourseSemester._

class CourseSemester(val courses: List[Course],
                     val startDate: EventDate,
                     val endDate: EventDate,
                     val createdUpdatedBy: CreatedUpdatedBy,
             ... there are so many attributes... ) {
  def totalCoursesInSemester: Int = courses.length
}

This allows me to do a match on a CourseSemester to the case class, so I can identify the class type in my pattern match. For example:

  val c = new CourseSemester(...)
  c match {
    case CourseSemesterCase(a) => { }
    case SomeOtherCase(b) => { }
  }

Is this a reasonable way to do it, or is there a better way?

You may use Type Ascription

c match {

    case cs : CourseSemester => // use cs
    case s : SomeOther       => // s is object of SomeOther type

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM