Reputation: 6462
I would like to create a variable with a dependent type.
I have
val a: Any = 5
and I would like to have
val b: [TypeOfA] = a
TypeOfA
must be the subtype of Any
(Int
, String
or MyClass
) and not Any.
I cannot use scala reflection since this code is part of a scalajs code (which is not a the JVM).
What I have tried:
trait DepValue{
type V
val value: V
}
def mk[T](x: T) = new DepValue{
type V = T
val value = x
}
But I don't get the result I want:
val x: Any = 5
magic(mk(x))
res70: Any = 5
I would like to have res70: Int = 5
It works well when the type is not Any
:
val y = 5
y: Int = 5
magic(mk(y))
res72: Int = 5
Is there any way do to that?
Upvotes: 0
Views: 50
Reputation: 2659
I think you're getting runtime and compile-time types mixed up. Your example is failing because when you say:
val x: Any = 5
magic(mk(x))
res70: Any = 5
You are explicitly telling the compiler that the type of x
is Any
, not Int
. So it's doing what you're telling it to: at compile-time, all it knows is that this is an Any
. (If you just said val x = 5
, it would work.)
I think what you're asking for is that the compiler should somehow infer that the type of x
is Int
. But because you told it that it's Any
, the compiler just plain doesn't know that any more at compile-time. The system only knows about that at runtime, which is much too late.
None of this really has much to do with dependent types per se -- it's more about the fact that you're hiding the type information, and the compiler can't just suss it out again...
Upvotes: 1