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.
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:
because types are not first class citizens
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.
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)
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?
My first stab:
class Decl[T] { type Type = T }
object Decl { def apply[T](x: T) = new Decl[T] }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With