Scala:自我类型注释 [英] Scala: self type annotation

查看:112
本文介绍了Scala:自我类型注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(试图通过探测边界来了解自身类型的使用.)

(Trying to understand the use of self types by probing the borders.)

这不能实例化(D和String是类,但是必须混用其中之一.加上String是最终的.).但是还有其他用途吗?

This cannot be instantiated (D and String are classes, but one of them has to be mixed in. plus String is final.). But is there any other use for it?

class D { 
    foo: String => 
    def f2 = foo.substring(1) 
}

更新:对不起,我似乎不善于提问. 我想知道的是这种奇怪的特殊情况是否有意义. D类永远无法实例化的情况,例如 1.我不能混入String,因为它不是目标. 2.我不能混入D,如.. 3.我不能扩展String,因为它是最终的.

Update: Sorry, I seem to be not good at asking questions. What I want to know is whether this strange special case makes sense. The case where class D can never be instantiated, as 1. I cannot mix in String, as it is not a tarit. 2. I cannot mix in D, as .. 3. I cannot extend String, as it is final.

推荐答案

自我类型注释通常有两个用途:

The self type annotation generally has two purposes:

  1. 强制实施某个基类/特征,并确保您的类或特征只能被该类型继承或混合,并且
  2. 实现内箱时请参考外箱. (如果不是这种语法,那么"this"指的是什么?)

我不确定我是否理解您的示例或其背后的原因.详细吗?

I'm not sure I understand your example or the reasoning behind it. Elaborate?

这篇关于Scala:自我类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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