繁体   English   中英

了解Scala类型参数化中的多个参数类型

[英]Understanding multiple parameter types in Scala Type Parameterization

我理解以下是scala中上限类型参数化的示例,其中T必须是Command的子类型。

def getSomeValue[T <: Command] = ...

但是,今天我发现了以下带有多个参数类型的类型参数化的实现,并且因为我是scala的初学者,所以我很难理解它实际上是做什么的。 这是否意味着T必须是Command,Foo或Bar的子类型?

def getSomeValue[T <: Command : Foo : Bar] = ...

这是否意味着T必须是Command,Foo或Bar的子类型?

不, T的上限仍然是必需的。 在调用此方法时,您现在还必须在范围内具有Foo[T]Bar[T]隐式实例。 这称为Context Bounds ,它的语法糖为:

def getSomeValue[T <: Command](implicit f: Foo[T], b: Bar[T])

如果您不知道隐含的含义, 请参阅文档以获取更多信息。

在类型参数规范中,独立冒号实际上是一个较长(相当复杂)的参数调用的简写(语法糖)。

示例: def f[N: Numeric](n: N) = ...

实际上是: def f[N](n: N)(implicit ev: Numeric[N]) = ...

这意味着当调用f(x)时,必须有一个与Numeric[x.type]匹配的隐式范围。

所以,在你的示例代码片段中: def getSomeValue[T <: Command : Foo : Bar] = ...

编译器大致将其转换为以下内容:

def getSomeValue[T <: Command](implicit ev1: Foo[T], ev2: Bar[T]) = ...

我们可以通过提供足够的骨架代码来实现它的可编译性来证明这一点。

class Command {}
class Foo[F] {}
class Bar[B] {}
class Cmd extends Command

def getSomeValue[T <: Command : Foo : Bar](t: T) = t

getSomeValue(new Cmd)(new Foo[Cmd], new Bar[Cmd])
                  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  // implicit parameters supplied explicitly

暂无
暂无

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

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