Jus12
Jus12

Reputation: 18034

Why define types in RHS rather than LHS?

Recently I came across some code that defines types as follows:

val a = "Hello":String 

rather than:

val a:String = "Hello"

Is there any advantage of the first notation? Maybe, perhaps in compilation?

Upvotes: 3

Views: 415

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

One marginal benefit I can think of is that the first notation can be used inside an expression, e.g. (a: String) + b, if you don't want to give the complete type or want to trigger an implicit conversion (of course, you can do both while still giving the type on the left as well). On the other hand, the second one:

  1. is required for recursive values and methods, as well as abstract members;

  2. is more widely used;

  3. doesn't require parentheses around the expression in cases like (a + b): String;

  4. allows you to see the signature more immediately if the definition takes more than one line.

I can't think of any other significant differences.

Upvotes: 4

Archeg
Archeg

Reputation: 8462

This is type ascription. It's basically a compile-time cast in scala. I don't feel like

val a = "Hello": String

is a proper use, it should be exactly the same as val a: String = "Hello" but it reads harder. You can check it in REPL: val b: String = 5 and val b = 5:String both generate compile-time error, when val b = 5.asInstanceOf[String] generates runtime error

However type ascription has a few very nice usages. a:_* is probably the most popular. You also able to trigger implicit conversions with it:

implicit def aToB(i: A): B = A.makeB()

(new A()) : B // will run A.makeB()

Upvotes: 0

Related Questions