简体   繁体   English

这个Scala类型参数声明是什么意思? [A:B]

[英]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 ) 原始定义来自“ autowire”项目

What does the [Result:Reader] and [Result:Writer] parts mean, exactly? [Result:Reader][Result:Writer]部分的确切含义是什么?

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. 它可以是T,但是T已用于特征定义中,因此作者为类型形参选择了更长的名称。

:Reader and :Writer - means that it should Reader and Writer type classes in scope for type Result :Reader和:Writer-表示它应该在Result类型范围内的Reader和Writer类型类

More about context bounds can be found here: http://docs.scala-lang.org/tutorials/FAQ/context-and-view-bounds.html 有关上下文范围的更多信息,请参见: 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. 但是,特质定义中根本不使用Result有点奇怪。 But totally ok. 但是,完全可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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