페이지

2015년 10월 20일 화요일

Scala2e Chapter2 First Steps in Scala - Step2. Define some variables

Step 2. Define some variables

val - final variable in Java. Once initialized, a val can never be reassigned

var - similar to a non-final variable in Java. A var can be reassigned throughout its lifetime

scala> val msg = "Hello, world!"
msg: String = Hello, world!

This example illustrates type inference, Scala’s ability to figure out types you leave off.
In this case, because you initialized msg with a string literal, Scala inferred the type of msg to be String.
Scala interpreter (or compiler) can infer type.

scala> val msg2: java.lang.String = "Hello again, world!"
msg2: String = Hello again, world!

scala> val msg3: String = "Hello yet again, world!"
msg3: String = Hello yet again, world!

The simple name of java.lang.String is String

scala> println(msg)
Hello, world!

scala> msg = "Goodbye cruel world!"
:6: error: reassignment to val
msg = "Goodbye cruel world!"


scala> var greeting = "Hello, world!"
greeting: String = Hello, world!

scala> greeting = "Leave me alone, world!"
greeting: String = Leave me alone, world!

scala> val multiLine =
| "This is the next line."
multiLine: String = This is the next line.

scala> val oops =
|
|
You typed two blank lines. Starting a new command.
scala>


댓글 없음: