gpt4 book ai didi

Scala 外部 => 语法

转载 作者:行者123 更新时间:2023-12-04 16:48:08 31 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
What does “outer =>” really mean?



我在哪里可以找到有关信息
trait After extends Context { outer => xxx
//...
}

什么意思 外 => ?

最佳答案

这是一种自我类型。您还可以添加类型注释,以强制将您的 trait 扩展为某种类型的类。但是没有类型,它只是对 this 的引用。 (并称为自引用),因此您可以在内部类等中使用它。例如:

class MyOuter { outer =>
// this == outer
class MyInner {
// this != outer
def creator = outer
}
}

例如,我提到的其他用法可用于向现有类添加特殊行为:
class MyClass {
val foo = "foo"
}

trait MyClassExtension { this: MyClass =>
def fooExtended(s: String) = foo + s
}

scala> val x = new MyClass with MyClassExtension
x: MyClass with MyClassExtension = $anon$1@5243618

scala> x.fooExtended("bar")
res3: java.lang.String = foobar

这里 this: MyClass =>意味着, MyClassExtension只能混入 MyClass 的实例或子类中.
scala> class OtherClass
defined class OtherClass

scala> val x = new OtherClass with MyClassExtension
<console>:11: error: illegal inheritance;
self-type OtherClass with MyClassExtension does not conform to MyClassExtension's selftype MyClassExtension with MyClass
val x = new OtherClass with MyClassExtension

关于Scala 外部 => 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666374/

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