Skip to content

Instantly share code, notes, and snippets.

@mrbkdad
Created July 19, 2018 01:46
Show Gist options
  • Save mrbkdad/8b3688b6392222b773630ab8f01d7299 to your computer and use it in GitHub Desktop.
Save mrbkdad/8b3688b6392222b773630ab8f01d7299 to your computer and use it in GitHub Desktop.
learning scala chapter 6
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. 오브젝트\n",
"- 싱글톤과 유틸리티 메소드를 위해 오브젝트 사용\n",
"- 클래스는 같은 이름의 companion 오브젝트를 가질 수 있음\n",
"- 클래스나 트레이트를 상속 할 수 있음\n",
"- apply 메소드는 보통 companion 클래스의 새 인스턴스를 생성 할 때 사용\n",
"- main 메소드를 피하기 위해 App 트레이트를 상속하는 오브젝트를 사용\n",
"- Enumeration 오브젝트를 확장하여 Enumeration을 구현 가능"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 싱글톤\n",
"- 자바처럼 정적 메소드가 필요없고 object 구문을 사용\n",
"- 최초 사용시 싱글톤 오브젝트 생성됨\n",
"- 클래스의 모든 기능을 사용 가능, 단 생성자 인자를 줄 수 없음(기본 생성자만 필요)\n",
"- 다음의 경우에 사용 된다\n",
" - 유틸리티 함수나 상수를 위한 공간\n",
" - 하나의 수정 불가능한 인스턴스가 효율적으로 공유될 수 있는 경우\n",
" - 어떤 서비스를 조정하기 위해 하나의 인스턴스가 필요한 경우(싱글톤 디자인 패턴)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"object Accounts{\n",
" private var lastNumber = 0\n",
" def newUniqueNumber() = {\n",
" lastNumber += 1\n",
" lastNumber\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Accounts.newUniqueNumber()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Accounts.newUniqueNumber()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 컴패니언 오브젝트\n",
"- 자바나 c++에서는 클래스가 인스턴스 메소드와 정적 메소드를 모두 갖는다.\n",
"- 스칼라는 companion 오브젝트를 이용한다.\n",
"- 반드시 같은 파일내에 존재해야 하며 private 에도 접근 가능하다.\n",
"- (참고) jupyter notebook에서는 테스트 용으로 같은 블럭 안에서 처리"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1"
]
},
{
"data": {
"text/plain": [
"Account$2@134102d7"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"var acc:Any = null\n",
"{\n",
" class Account{\n",
" val id = Account.newUniqueNumber()\n",
" private var balance = 0.0\n",
" def deposit(amount:Double) { balance += amount }\n",
" def withdraw(amount:Double){ balance -= amount }\n",
" }\n",
" object Account{\n",
" private var lastNumber = 0\n",
" private def newUniqueNumber() = { lastNumber += 1; lastNumber}\n",
" }\n",
" acc = new Account\n",
" acc.asInstanceOf[Account].deposit(100)\n",
" print(acc.asInstanceOf[Account].id)\n",
"}\n",
"acc"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### apply 메소드\n",
"- object(arg1, ..., argN) 이런 형태의 식에서 호출됨\n",
"- 보통 companion 클래스의 오브젝트 리턴\n",
"- new를 사용하는 것보다 여러 부분에서 편리함 : 예) Array(Array(1,2),Array(3,4))\n",
"- new 는 this 생성자가 호출된다."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"110.0"
]
},
{
"data": {
"text/plain": [
"Account$2@5302c18c"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"var acc:Any = null\n",
"{\n",
" class Account(val id: Int, initBalance: Double){\n",
" private var balance = initBalance\n",
" def deposit(amount:Double) { balance += amount }\n",
" def withdraw(amount:Double){ balance -= amount }\n",
" def current = balance\n",
" }\n",
" object Account{\n",
" def apply(initBalance:Long) = new Account(newUniqueNumber(), initBalance)\n",
" private var lastNumber = 0\n",
" private def newUniqueNumber() = { lastNumber += 1; lastNumber}\n",
" }\n",
" acc = Account(10)\n",
" acc.asInstanceOf[Account].deposit(100)\n",
" print(acc.asInstanceOf[Account].current)\n",
"}\n",
"acc"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Application object\n",
"- def main(args: Array[String]){ ... }\n",
"- App 트레이트 상속\n",
"- App 트레이트 상속한 경우 실행시 scala.time 옵션을 지정하면 프로그램 종료시 경과 시간을 표시한다.\n",
"<pre>\n",
"$ scalac Hello.scala\n",
"$ scala -Dscala.time Hello Fred\n",
"Hello Fred\n",
"[total **ms]\n",
"</pre>"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"object Hello{\n",
" def main(args: Array[String]){\n",
" println(\"Hello World!\")\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"object Hello extends App{\n",
" println(\"Hello World!\")\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"object Hello extends App{\n",
" if(args.length > 0)\n",
" println(\"Hello \" + args(0))\n",
" else\n",
" println(\"Hello World!\")\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Enumeration\n",
"- 스칼라는 이뉴머레이션 타입이 없음\n",
"- Enumeration 클래스를 이용하여 생성\n",
" - Enumeration 상속 오브젝트 정의\n",
" - Value 메소드를 이용하여 이뉴머레이션 초기화\n",
" - Value 메소드는 ID와 값을 할당한다.\n",
" - ID는 기본값으로 0부터 순차적으로 지정하며 값은 필드명을 기본값으로 한다.\n",
" - 이 이뉴머레이션의 타입은 enumeration.Value 이며 type을 지정할 수 있다.\n",
" - 각 값은 id와 toString 메소드를 제공한다\n",
" - ID로 찾거나 이름으로 값을 찾을수 있다. enumeration(id), enumeration.withName(name)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"object TrafficLightColor extends Enumeration{\n",
" val Red, Yello, Green = Value\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Red"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor.Red"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"TrafficLightColor.ValueSet(Red, Yello, Green)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor.values"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Yello"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor(1)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"hurry up"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"{\n",
" import TrafficLightColor._\n",
" def doWhat(color: Value) = {\n",
" if(color == Red) \"stop\"\n",
" else if(color == Yello) \"hurry up\"\n",
" else \"go\"\n",
" }\n",
" doWhat(Yello)\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"object TrafficLightColor extends Enumeration{\n",
" type TrafficLightColor = Value\n",
" val Red = Value(10,\"stop\")\n",
" val Yello = Value(20,\"hurry up\")\n",
" val Green = Value(30,\"go\")\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"hurry up"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"{\n",
" import TrafficLightColor._\n",
" def doWhat(color: TrafficLightColor) = {\n",
" if(color == Red) \"stop\"\n",
" else if(color == Yello) \"hurry up\"\n",
" else \"go\"\n",
" }\n",
" doWhat(Yello)\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"go"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor.Green"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 : stop\n",
"20 : hurry up\n",
"30 : go\n"
]
}
],
"source": [
"for(c <- TrafficLightColor.values) println(c.id + \" : \" + c.toString)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"30"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor.Green.id"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"go"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"TrafficLightColor.Green.toString"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"stop\n"
]
}
],
"source": [
"//이름으로 찾기\n",
"println(TrafficLightColor.withName(\"stop\"))"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"stop\n"
]
}
],
"source": [
"//ID로 찾기\n",
"println(TrafficLightColor(10))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Apache Toree - Scala",
"language": "scala",
"name": "apache_toree_scala"
},
"language_info": {
"file_extension": ".scala",
"name": "scala",
"version": "2.11.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment