scala - 将特征限制为对象?

标签 scala traits singleton-type

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

trait OnlyForObjects {
  this: ... =>
}

object Foo extends OnlyForObjects  // --> OK

class Bar extends OnlyForObjects   // --> compile error

最佳答案

是的!有一个晦涩难懂且几乎没有记录的 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
                         ^

language specification 中多次提到它,但甚至没有出现在 API 文档中。

关于scala - 将特征限制为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25406698/

相关文章:

scala - 如何制作一个右关联的中缀运算符?

scala - 字符串插值和宏 : how to get the StringContext and expression locations

dataframe - 如何在 Spark Dataframe 中显示完整的列内容?

Rust:为关联类型实现特征 "From"(错误)

c++ - 尝试使用未知类型的模板非类型参数

haskell - Sigma 中的限制类型

Scala函数部分应用

rust - 无法调用 fn<T : X> from an impl<T: X> because X is not satisfied for T

haskell - 使用haskell的单例,如何编写 `fromList::[a] -> Vec a n` ?

scala - 在 Scala 2.11+ 中如何准确地使用单例类型作为类型证据?