Skip to content

Instantly share code, notes, and snippets.

@oxbowlakes
Created October 4, 2012 07:14
Show Gist options
  • Save oxbowlakes/3831945 to your computer and use it in GitHub Desktop.
Save oxbowlakes/3831945 to your computer and use it in GitHub Desktop.
Vals in Scala
// The declaration of a value in scala looks like this:
val x = 1
// ^ ^ ^
// ^ ^ the value we wish to assign our new value to
// ^ identifier (ie name of value)
// type of value (val or var)
// Each identifier in scala has an associated type (or, more accurately, it has many types ranging from the least to the most specific)
// x has the types Any, AnyVal and Int (which is the most specific)
// We can ascribe a type to the identifier "x", rather than let the compiler infer it for us. The following are all allowable:
val x: Int = 1
val y: AnyVal = 1
val z: Any = 1
// We can ascribe a type if there is an *implicit conversion* in scope which would convert the rhs into this type:
val dec: BigDecimal = 1
// What is the difference between x, y and z (above)?
x + y //WILL NOT COMPILE!
y + z //WILL NOT COMPILE!
// The key lesson here is always to maintain a clear distinct in your mind between values that the compiler sees and values that the runtime sees.
// In each case, the value for x, y and z at runtime is Int. You could stop your running program to inspect the type of x, y and z and it will be
// Int in each case.
// However, the compiler does not know this: it only "sees" y as being of type AnyVal; it therefore only thinks you can do the sort of things with y which you
// can do with AnyVal (i.e. not much). There's no difference at a *language level* between these two declarations
val i: AnyVal = 1
val b: AnyVal = true
// At runtime, we can discover the *true type* of i and b using the method isInstanceOf:
i.isInstanceOf[Int] //true
b.isInstanceOf[Int] //false
// We can create a new reference by using the method asInstanceOf:
b.asInstanceOf[Boolean]
// Note that this does nothing to the type of the reference b, which is still AnyVal. This is often called "casting" one type into another. What happens when you cast wrongly?
b.asInstanceOf[Int]
// Note the *compiler* could not know whether this cast was definitely valid or otherwise. The fact that it is invalid will only be discovered at runtime,
// where a ClassCastException will be thrown.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment