简体   繁体   中英

What does this Scala type-parameter declaration mean? [A:B]

Recently I've seen a trait that resembles this definition:

trait Server[T, Reader[_], Writer[_]] {
  def read[Result:Reader](t: T): Result
  def write[Result:Writer](r: Result): T
}

(The original definition is taken from the "autowire" project )

What does the [Result:Reader] and [Result:Writer] parts mean, exactly?

How is it to be interpreted? What is the relationship between Reader, Writer and Result?

Result - type parametrization for read and write methods. It can be T, but T is already used in trait definition, so author picked a bit longer name for type parameter.

:Reader and :Writer - means that it should Reader and Writer type classes in scope for type Result

More about context bounds can be found here: http://docs.scala-lang.org/tutorials/FAQ/context-and-view-bounds.html

This can be rewritten in this way:

trait Server[T, Reader[_], Writer[_]] {
  def read[Result](t: T)(implicit reader: Reader[Result]): Result
  def write[Result](r: Result)(implicit writer: Writer[Result]): T
}

However it's a little strange that Result is not used at all in trait definition. But totally ok.

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