scalaobjecttraitssubtypesupertype

Scala - Trait returns different objects


I have a question about traits in Scala.

I have a trait returns a type of object (AA or BB) depending on the value of parameter country.

My implementattion covers the following approach:

trait firstT{

  def GetType(country: String) : OType =  {
      //i would like to call OType.load(country)
  }
}


  trait OType[T <: OType[T]] {
        def load(country: String): OType[T] = ??? 
        //I would like to return AA or BB depending on country
    }

class AA extends OType[AA] {
  override def load(country: String): AA = new AA
}



class BB extends OType[BB] {
  override def load(country: String): BB = new BB
}

Could you please help me on this? Thank you Best Regards


Solution

  • load is a "static" method of the trait so it belongs in the companion object not the class definition.

    So the code you want might look like this

    trait firstT {
      def GetType(country: String): OType = {
        OType.load(country)
      }
    }
    
    trait OType
    
    object OType {
      def load(country: String): OType =
        if (country == "AA") {
          AA.load()
        } else {
          BB.load()
        }
    }
    
    class AA extends OType
    
    object AA {
      def load(): AA = new AA
    }
    
    class BB extends OType
    
    object BB {
      def load(): BB = new BB
    }
    

    If you really need the OType trait to be parameterised by type then use an abstract type member:

    trait OType {
      type T <: OType
    }
    
    class AA extends OType {
      type T = AA
    }
    
    class BB extends OType {
      type T = BB
    }