将特征限制为对象? [英] Restricting a trait to objects?

查看:70
本文介绍了将特征限制为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制一个特征,使其只能混合到对象中?例如

Is there a way to restrict a trait so that it can only be mixed into objects? E.g.

trait OnlyForObjects {
  this: ... =>
}

object Foo extends OnlyForObjects  // --> OK

class Bar extends OnlyForObjects   // --> compile error

推荐答案

是的!有一个晦涩难懂且几乎没有记录的 scala.Singleton:

Yes! There's the obscure and mostly undocumented scala.Singleton:

scala> trait OnlyForObjects { this: Singleton => }
defined trait OnlyForObjects

scala> object Foo extends OnlyForObjects
defined module Foo

scala> class Bar extends OnlyForObjects
<console>:15: error: illegal inheritance;
 self-type Bar does not conform to OnlyForObjects's selftype OnlyForObjects
 with Singleton
       class Bar extends OnlyForObjects
                         ^

语言规范中多次提到,但在API 文档.

It's mentioned a few times in the language specification, but doesn't even appear in the API documentation.

这篇关于将特征限制为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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