Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala – How to create a class with a constructor that receives an object as parameter

Igot two classes in Scala – one is a property of the other. I want to create a smart constructor for the parent class, but I don’t really know what are the best practices to do it. I’ve done some research, but didn’t find a satisfactory solution/explanation.

Here are my classes.

final class Role(role: String) //child

object Role:
  def isRoleValid(role: String): Boolean =
    val pattern = "([a-zA-Z])+".r
    pattern.matches(role)
      
  def newRole(role: String): Role = Role(role)
    
  def from(role: String): Option[Role] =
    if(isRoleValid(role)) Some(newRole(role))
    else None
final class NurseRequirement(role: Role, number: Int) //Parent

object NurseRequirement:
  def isNumberValid(number: Int): Boolean = number > 0
  //What should I do to validate the Role object??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I strongly suspect that you actually wanted companion object with something like this:

  def from(s: String, n: Int): Option[NurseRequirement] =
    if isNumberValid(n) 
    then Role.from(s).map(NurseRequirement(_, n))
    else None

If you get into situation where you have more of such optional subcomponents, you can get rid of the nested ifs by using the for-comprehensions on Option, i.e. something like:

  def from(s: String, n: Int) =
    for
      r <- Role.from(s)
      m <- Option(n).filter(isNumberValid)
    yield NurseRequirement(r, m)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading