gpt4 book ai didi

scala - 使用依赖方法类型和类型投影时的类型等价问题

转载 作者:行者123 更新时间:2023-12-04 06:20:34 25 4
gpt4 key购买 nike

我正在使用 Scala 2.10.0-M1 尝试以下操作:

trait Container {
type X
}

class Test[C <: Container](val c: C) {
def foo(x: c.X): C#X = x // this compiles fine
def bar(x: C#X): c.X = x // this does not compile
}

使用这种形式时问题是一样的:

def bar[C <: Container](c: C)(x: C#X): c.X = x

我真的不明白为什么 foo 可以编译而 bar 不能。

我相信 c.XC#X 在这里应该是一样的。

另外,我不明白错误信息:

[error]  found   : x.type (with underlying type C#X)
[error] required: Test.this.c.X
[error] possible cause: missing arguments for method or constructor
[error] def bar(x: C#X): c.X = x // this does not compile

有什么想法吗?

最佳答案

C#X 表示来自任何 CXc.X 表示来自您的特定 CX,即 c。后者更具体!

例如,如果X 是一个账单,c 是一个特定的客户,c.X 意味着该方法只接受来自(对于,大概)客户 cC#X 表示它接受来自任何客户的任何账单。如果您想确保客户只需要支付他们自己的账单(至少在默认情况下),前者就是您想要的。

关于scala - 使用依赖方法类型和类型投影时的类型等价问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9057858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com