Home > Enterprise >  Scala - How to create a class with a constructor that receives an object as parameter
Scala - How to create a class with a constructor that receives an object as parameter

Time:04-26

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??

CodePudding user response:

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)
  • Related