简体   繁体   中英

Enforcing the type of a Scala trait using a generic

Essentially, I am trying to do the following:

trait Foo[T] extends T {
  def json: Writes[T]
  def bar: String = {
    Json.toJson[T](this)(json).toString
  }
}

I want the compiler to enforce that any class using trait Foo is of type T. Unfortunatly, 'extends T' is not valid. Right now, the best I can do is the following:

trait Foo[T] extends T {
  def json: Writes[T]
  def bar: String = {
    Json.toJson(this.asInstanceOf[T])(json).toString
  }
}

But obviously, the compiler isn't enforcing anything. Is there anyway to achieve what I want?

You can use a self type to require that any class extending Foo[T] also be an instance of T :

import play.api.libs.json._

trait Foo[T] { self: T =>
  def json: Writes[T]
  def bar: String = Json.toJson[T](self)(json).toString
}

You can use whatever name you want in place of self (which is just a common convention).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM