Query on type in Scala

I have following:

class A(x:Int)
val a = new A

So a is of type A. And then we have a.type. Are following two same?

val b:a.type = a
val b:A = a

Not the same - a.type is a sub-type of A:

**Welcome to Scala 2.12.4 (OpenJDK 64-Bit Server VM, Java 1.8.0_161).
Type in expressions for evaluation. Or try :help.

class A
defined class A

val a = new A

val b1: A = a
b1: A = A@3134153d

val b2: a.type = a
b2: a.type = A@3134153d

def print1(aa: A): Unit = println(aa)
print1: (aa: A)Unit

def print2(aa: a.type): Unit = println(aa)
print2: (aa: a.type)Unit

print1(b1)
$line3.$read$$iw$$iw$A@3134153d

print1(b2)
$line3.$read$$iw$$iw$A@3134153d

print2(b1)
:14: error: type mismatch;
found : b1.type (with underlying type A)
required: a.type
print2(b1)
^

print2(b2)
$line3.$read$$iw$$iw$A@3134153d**

Best, Oliver

1 Like

@mghildiy, the thing to keep in mind is that Type means essentially “what can go in here”.

So when you say : A , that means that any object of type A can go into it. But : a.type means that only the specific object a can go into it.

Type is very different from runtime class. At runtime, the object is the object – it’s the same pointer. (Which is what the println()s above show.) But at compile time, you can use Types to be much more precise about what is and isn’t allowed.

1 Like

So is it safe to say following:
When we create a class,A, we basically introduce a new type in program’s system. And we can have multiple objects/instances of type A. Its like what we have in Java.
In scala,when we create an object/instance(like, val a = new A), then we are not only creating an instance but we are also introducing a new type in program’s system(here,a.type). And we can only have single instance of a.type, and that is a itself.

Hi @curoli,

val b2: a.type = a

Here we are stating that b2 is of type a.type, and then we assign a to it.But a is of type A,and A is supertype of a.type. So we are assigning a supertype to its subtype. Is a implicity cast to a.type here?

Also,

val b = a

So here what is the inferred type for b:A or a.type?

Since a is of type a.type, it is not a cast. The Scala shell reports a to be of type A, because that is normally more useful to know.

1 Like