gpt4 book ai didi

scala - 如何使用带有 `self` 引用的 Scala 特征?

转载 作者:行者123 更新时间:2023-12-03 09:18:40 24 4
gpt4 key购买 nike

我看到一些代码编写特性如下:

trait SelfAware { self: Self =>
....
}

class Self
val s = new Self with SelfAware // this is ok
println(s.self) // error happened

class X
new X with SelfAware // error happened here

我想知道为什么会发生错误以及如何以这种方式使用 trait?

最佳答案

发生错误是因为您限制了 this 的类型引用(您已将其命名为 self )类型为 Self .当你说 new Self with SelfAware ,这是可以的,因为该对象的类型是 Self就像你问的那样。但是当你说 new X with SelfAware ,没有证据表明 X无论如何都是 Self 的子类型.

在类型为 X with SelfAware 的新对象中,它的类型是什么 self成员?好吧,它不会是 Self 类型的,但类型为 X .但是你已经定义了特征 SelfAware以便 self必须是 Self 类型,所以你会得到一个类型错误。

关于scala - 如何使用带有 `self` 引用的 Scala 特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291176/

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