Blankman
Blankman

Reputation: 266900

How to make sure classes that use trait have certain classes in them?

I want to create a trait, but I want all classes that will use this trait to have certain classes on them:

trait SomeHelper {
  def homeUrl(): String =
    s"$website.url"
}

class Foo(website: Website) extends SomeHelper {
  val hello = homeUrl + "/hello"
}

How do I make a requirement on the trait user to have the website class?

Upvotes: 1

Views: 49

Answers (1)

flavian
flavian

Reputation: 28511

In hope I've understood your requirement:

trait SomeHelper { self: Website =>
  def homeUrl(): String = s"$url"
}

Every implementor of SomeHelper must now extend Website or mixin Website.

If you don't want extension, traits are designed to contain unimplemented members as well as implemented ones you could simply:

 trait SomeHelper {

   def website: Website

   def homeUrl(): String = s"$website.url"
 }

On a side note, by convention methods with no side effects such as homeUrl() should not have ().

Update

If you have more than one trait, you can simply add more to the restriction:

trait Website {
  def url: String
}
trait Portal {
  // whatever you want here, I'm making stuff up
  def identity: String
}
trait SomeHelper { self: Website with Portal =>
  // when you mixin with a self type bound, you can call methods directly
  def homeUrl: String = s"$url:$identity"
}

Upvotes: 6

Related Questions