如何使用带有`self`引用的scala特征? [英] How to use scala trait with `self` reference?

查看:49
本文介绍了如何使用带有`self`引用的scala特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw some code write trait as following:

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?

I'd like to know why the error happened and how to use trait in this way?

推荐答案

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

The error is occurring because you have constrained the type of the this reference (which you have named self) to be of type Self. When you say new Self with SelfAware, this is OK, because that object is of type Self like you asked. But when you say new X with SelfAware, there is no evidence that X is in any way a subtype of Self.

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

In your new object of type X with SelfAware, what would be the type of its self member? Well, it would not be of type Self, but of type X. But you have defined the trait SelfAware so that self must be of type Self, so you get a type error.

这篇关于如何使用带有`self`引用的scala特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆