Scala Tutorial 번역 - Unified Types, Mixin and Composition
Unified Types
자바와는 대조적으로, Scala에서는 아래에 명시된 모든 값은 객체들이다.
- 원시 변수 타입 (primitive type)
- numberic
- byte
- short
- int
- long
- float
- double
- boolean
- char
- 객체 타입 (reference type)
- Class를 통해 생성되는 모든 객체
Scala Class Hierarchy
아래의 figure1.1를 통해 Scala 타입의 계층 정보를 한눈에 볼 수 있다.
figure1.1
Scala에서의 최상위 클래스는 scala.Any 클래스이다. 그리고 아래와 같은 두개의 하위 클래스를 가진다.
scala.AnyVal
값을 표현하는 최상위 클래스이며, 자바에서의 원시타입들로 표현되는 값을 나타내는 모든 클래스들로 이미 scala에서도 미리 모두 정의가 되어 있다.
scala.AnyRef
참조 객체를 표현하는 최상위 클래스이며, 사용자 정의 클래스들은 직,간접적으로 AnyRef클래스들을 상속받게 된다. 그리고 사용자 정의 클래스들은 간접적으로 trait인 scala.ScalaObject를 상속받는다. 하지만 scala가 실행되는 환경(예, JVM)에서 제공된느 클래스들은 scala.ScalaObject를 상속받지 않는다. 그렇지만 JVM에서 scala가 실행될 경우, AnyRef는 java.lang.Object에 대응된다. 아래의 예제를 참조하면 scala의 type을 이행하는데 도움이 될 것이다.
import scala.collection.mutable
object UnifiedTypes extends App {
//모든 타입의 변수를 저장할 수 있다
val set = new mutable.LinkedHashSet[Any]
set += "This is a string" // string type의 값 추가
set += 732 // int type의 값 추가
set += 'c' // char type의 값 추가
set += true // boolean type의 값 추가
set += main _ // main function 추가
val iter:Iterator[Any] = set.iterator;
while(iter.hasNext){
val e: Any = iter.next()
println("Type: " + e.getClass() + " value: " + e.toString)
}
}
Output
Type: class java.lang.String value: This is a string
Type: class java.lang.Integer value: 732
Type: class java.lang.Character value: c
Type: class java.lang.Boolean value: true
Type: class UnifiedTypes$$anonfun$1 value: <function1>
Classes
Scala에서의 class는 동일한 속성 및 행위를 가지는 객체를 생성할 수 있는 정적인 template을 의미한다. (* Java에서도 이와 같은 의미로 사용된다.) 아래는 Point class정의를 보여준다.
Point class
class Point(var x: Int, var y: Int) {
def move(dx: Int, dy: Int): Unit = {
x = x + dx;
y = y + dy;
}
override def toString: String = "(" + x + ", " + y + ")"
}
Create Point and print toString
object _main {
def main(args: Array[String]): Unit = {
val p: Point = new Point(0, 0)
p.move(10, 30)
println(p.toString())
}
}
Define Variables
Immutable variable(불변 변수)
val 키워드를 사용하여 변수를 선언할 경우, 이는 Java에서 final로 선언한 변수와 동일하다. 즉, 변수에 값을 할당하게 되면, 그 이후로 값을 재 할당할 수 없다.
