njk2015 njk2015 - 1 year ago 79
Scala Question

What does this scala expression mean? val h3 : Holder[Person] = h2

I have been following some online tutorials in order to learn Scala. I came across the following code snippet:

class Holder[+T](val value: T) {
def printIt = println(value)
}

val h1 = new Holder(3)
h1.printIt

class Person
class Employee extends Person

val h2 = new Holder(new Employee)
val h3 : Holder[Person] = h2


Unfortunately the teacher did not explain what the
val h3
expression does, with regards to the
:
colon. Could someone enlighten me?

Answer Source

That is a type Annotation, Scala can automatically figure out the type of a variable (called type inference), which is what would happen in you just used val h3. But you can specify the type explicitly if you need. so val h3: Holder[Person] Means the value h3 has the type Holder[Person]

You may want to do this for a couple of reasons. The first is documentation. If you specify the type you make it clear what type the variable or method has so you don't need to think about it. It also causes an error if you accidentally make a mistake and try to put the wrong type into the variable. Typically, things like local and private members it isn't necessary to clutter up the code with type annotations, but it's a good idea to include them for any public fields or methods.

The other reason is because you want a different type than the inference determines is appropriate. Usually (as is the case in the example) it's because the actual object you are assigning is a subtype of the type you want for your method or variable. In the example, h2 has the type Holder[Employee] so that's the type Scala would infer for h3 as well, but we want the type of h3 to be a supertype, Holder[Person] so we explicitly include the type annotation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download