3

I am curious as to why I am able to re-declare the type of a type-paramertized argument to a scala function like this:

// original 

def ident[T](z:T) = z
def echo[T](x:T) = {
    ident(x)
} 
echo("hi")

Which behaves exactly the same as this:

// modified with what seems to be a useless re-specification of the original type 


def ident[T](z:T) = z
def echo[T](x:T) = {
    ident(x:T)    //  <<< ---  we specify type 'T' here, but not in the orig
} 
echo("hi")

What is this language construct called? Does it have a name? And are there circumstances in which it would actually be useful?

Wandering Fool
  • 2,170
  • 3
  • 18
  • 48
Chris Bedford
  • 2,560
  • 3
  • 28
  • 60

1 Answers1

4

It's called type ascription. It's similar to a type cast, but not quite. i.e. if the type is not compatible, there will be a compiler error. So in that it is also like a type-check. If you say x: T, you're telling the compiler you expect x to be a T. If x is a T, then it will be treated as precisely a T.

How is it useful? You can use it to up-cast a bottom-type like null:

ident(null: T)

Or simply up-cast some non-null object.

In the context of your question, the ascription does nothing. We already know x is a T. But if we try to do it with something else..

class Z

scala> def test[T](t: T): T = { val z = new Z; ident(z: T) }
<console>:9: error: type mismatch;
 found   : z.type (with underlying type Z)
 required: T
       def test[T](t: T): T = { val z = new Z; ident(z: T) }
                                                     ^

I primarily use it for type-checking while debugging code, in order to get more refined error messages (i.e. make sure the types are what I think they are).

Some concrete examples:

scala> val x = 1: Short
x: Short = 1

scala> val x = 1: Long
x: Long = 1

scala> val l = Nil: List[Int]
l: List[Int] = List()
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • Thanks ! i am now unconfused. And, I found this posting very useful as well> http://stackoverflow.com/questions/2087250/what-is-the-purpose-of-type-ascriptions-in-scala – Chris Bedford Aug 14 '15 at 03:11