为什么 Scala 没有 decltype? [英] Why Scala does not have a decltype?
问题描述
有时可能希望将 x
声明为与 y
相同的类型.使用 vals
类型推断可以很好地处理这个问题,但这在其他一些领域不起作用,比如 使用函数类型.
Sometimes one might want to declare x
to be of the same type as y
. With vals
type inference handles this very well, but this does not work in some other areas, like with function types.
对于具有一些 C++ 经验的程序员来说似乎显而易见的解决方案是 decltype.当前的 Scala 中似乎没有这样的设施.
A solution which seems obvious to a programmer with some C++ experience would be a decltype. No such facility seems to be present in current Scala.
对链接问题的回答说明:
An answer to the linked questions tells:
因为类型不是一等公民
我不得不承认我不明白这一点.我不认为类型是 C++ 中的一等公民,但它仍然可以具有 decltype
.对于泛型中的类型参数或类似的东西,我不会询问诸如 decltype
之类的东西(我知道泛型不是模板,类型在其中被删除).尽管如此,我认为一个允许我在需要类型的地方使用表达式类型的运算符 - 当然编译器必须能够评估表达式类型,否则 val
的类型推断定义是不可能的.
I have to admit I do not understand this. I do not think types are a first class citizens in C++, but still it can have the decltype
. I am not asking about anything like decltype
for type parameters in generics or anything like that (I understand generics are not templates and the types are erased in them). Still, I think an operator which would allow me to use a type of an expression in a place where a type is expected - certainly the compiler must be able to evaluate an expression type, otherwise type inference for val
definition would not be possible.
decltype
可以像下面这样使用 - 代码没有尝试做任何有用的事情,只是为了说明语法和基本用法:
A decltype
could be used like below - the code is not trying to do anything anything useful, just to illustrate the syntax and basic usage:
case class A(x:Int = 0)
val a = new A(10)
val b = new decltype(a)
def f(c:decltype(a)) : decltype(a.x+a.x)
缺少 decltype
是一个深思熟虑的决定,还是有一些特定的原因导致 Scala 不能拥有它?是否有一些使用编译时反射的解决方案可以实现这一点?
Is absence of decltype
a deliberate decision, or are there some specific reasons why Scala cannot have it? Is there perhaps some solution using compile time reflection which would allow this?
推荐答案
我的第一次尝试:
class Decl[T] { type Type = T }
object Decl { def apply[T](x: T) = new Decl[T] }
例如,如果我们有一些变量 x
我们不想明确声明其类型:
For example, if we have some variable x
whose type we don't want to state explicitly:
val d = Decl(x)
type TypeOfX = d.Type
这篇关于为什么 Scala 没有 decltype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!