如何确保使用trait的类中包含某些类?

Bla*_*man 1 scala traits

我想创建一个特征,但是我希望所有使用这个特征的类都有一些特定的类:

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

class Foo(website: Website) extends SomeHelper {
  val hello = homeUrl + "/hello"
}
Run Code Online (Sandbox Code Playgroud)

如何要求特质用户拥有网站类?

fla*_*ian 6

希望我理解你的要求:

trait SomeHelper { self: Website =>
  def homeUrl(): String = s"$url"
}
Run Code Online (Sandbox Code Playgroud)

每个SomeHelper必须现在extend Website或者混合的实现者Website.

如果您不想要扩展,则traits旨在包含未实现的成员以及您可以简单地实现的成员:

 trait SomeHelper {

   def website: Website

   def homeUrl(): String = s"$website.url"
 }
Run Code Online (Sandbox Code Playgroud)

在旁注,按惯例方法没有副作用,如homeUrl()不应该().

更新

如果您有多个特征,您只需添加更多限制:

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"
}
Run Code Online (Sandbox Code Playgroud)