Scala: “Static values” in traits?

浪尽此生 提交于 2019-12-06 11:04:06

If you can relax the requirement that XDependent has to be a trait, and make it an abstract class instead, then it seems as if a typeclass which provides a single null-ary method x is exactly what you want:

Here is your base trait X (without X.x or anything, that wouldn't be "static"):

trait X

Now you can define a typeclass HasStaticX[T] that guarantees that for a type T we can give some string x:

trait HasStaticX[T] {
  def x: String
}

Then you can use it like this:

abstract class XDependent[T <: X : HasStaticX] {
  def printX: String = implicitly[HasStaticX[T]].x
}

What HasStaticX does is essentially building a compile-time partial function that can take type T and produce a string-value x associated with T. So, in a way, it's something like a function that takes types and returns values. If this is what you want, then nothing has to be done to for "integrating static values", it just works in the current non-experimental mainstream versions of Scala.

The "value-dependent types" would be exactly the other way round: those would be essentially "functions" that assign types to values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!