[SOLVED] Trait method in type class returns the trait itself question

Suppose I have a trait called MyTrait

trait MyTrait[T] {
    def method[A](value: A): MyTrait[T]
}

In the companion object I want to implement method, but I do not know how to return the trait itself because if the code new MyTrait[TypeA] { ... } then it will become an infinite cycle.

object MyTrait {
    val instance = new MyTrait[TypeA] {
        override def method[A](value: A) = ???
    }
}

What I can think of is to return this in the end. But that’s seemingly not functional because it shares the instance.

So my question. Is there a way to achieve this (i.e. method return a new MyTrait instance)? Or generally it’s not doing so in type class? Any suggestions?

Thanks

What should method return in your case? Itself? Another instance, if so which one?

The trait MyTrait’s method will return MyTrait as specified in the trait

trait MyTrait[T] {
    def method[A](value: A): MyTrait[T]
}

I am asking in your implementation, what should it do.

Maybe a concrete example would be easier to explain the effect I want to achieve. Suppose I have a Setting trait.

trait Setting[T] {

    def set[A](key: String, value: A): Setting[T]

}

The implementation I would try is (but I do not know how to achieve the effect that it can return a new instance of Setting type without repeating the code)

object Setting {
    implicit val setting = new Setting[typesafe.Config] {
        override def set[A](key: String, default: A): Setting[Config] = new Setting[typesafe.Config] {
            override def set[A](key: String, default: A): Setting[Config] = new Setting[typesafe.Config] { 
                 .... // this becomes infinite new Setting and override set method 
            }
        }
    }
}

Why not just having a class?

sealed trait Setting[T] {
  def set[A](key: String, value: A): Setting[T]
}

object Setting {
  private final class SettingImpl extends Setting[typesafe.Config] {
    override def set[A](key: String, default: A): Setting[typesafe.Config] =
      new SettingImpl() // I guess some logic here.
  }

  implicit final val setting: Setting[typesafe.Config] = new SettingImpl()
}
1 Like

That passed on my head but I didn’t pick it up. Thanks for the advice. It does help and simpler!