프로그래밍 언어 실습 세 번째

Scala 기초 2

       

튜토리얼 진행 시 어려운 점이 있으면 Ed Discussion 게시판을 이용해 질문하세요. 게시판을 통해 하기 어려운 질문이라면 아래 TA 이메일을 통해 문의하시기 바랍니다.

   

조교: Aditi(diwakarmzu@gmail.com)

   

또한 본 자료는 아래의 인터넷 자료들을 참고하여 만들어졌으니 추가적으로 궁금한 점이 있으면 참고하시기 바랍니다.

           


1. apply 메소드
  • apply를 정의하면 메소드를 호출하듯 객체를 호출할 수 있다.
class Foo {
    def apply() = 0
}
object Foo_test {
  def main(args: Array[String]): Unit = {
      val foo = new Foo
      println(foo())
    }
}
  • Foo_test 실행 화면

title

   

2. 객체
  • object로 선언하는 객체
object Timer {
  var count = 0

  def currentCount(): Long = {
    count += 1
    count
  }
}
object Timer_test {
  def main(args: Array[String]): Unit = {
    for(i <- 1 to 10) {
      println(Timer.currentCount())
    }
  }
}
  • Timer_test 실행 결과

title

   

3. 반복문

간단하게 1부터 10까지 출력하는 반복문을 만들어보겠습니다.

  • for (i <- 시작 to 끝) 의 형식으로 1부터 10까지 포함합니다.
for (i<- 1 to 10) {
	print(i + "\t")
}
  • for문 실행 결과

title

to 대신 until을 쓰는 경우도 있다 !!

for (i<- 1 until 10) { // 위의 코드에서 to를 until로만 바꾸었다.
	print(i + "\t")
}
  • for문에서 until 실행 결과 : to와 달리 10이 포함되지 않는것을 볼 수 있다.

title

  • while
var i = 1
while (i <= 10) {
	print(i + "\t")
	i += 1
}
  • while문 실행 결과

title

   

4. 조건문
  • 한 줄로 쓸 수 있다.
val num = 10
val result = if(num>0) 1 else -1
println(result)
  • result

title

  • if, else if, else
val n = 10
if (n < 0) {
	println("n은 음수입니다.")
}
else if ( n == 0) {
	println("n은 0입니다.")
}
else {
	println("n은 양수입니다.")
}

title

   

5. 패턴 매칭
  • case문을 순서대로 검사하다가 조건에 맞는 case를 만나면 해당 코드를 실행한다.
print(MatchTest(2))

def MatchTest(x:Int):String = x match {
    case 1 => "one"
    case 2 => "two"
    case 3 => "three"
}

match

  • match를 사용하면 타입 다른 경우도 타입에 따라 실행이 가능하다.
def use_match(o: Any): Any = {
    o match {
        case i : Int if i < 0 => i-1 // int형
        case i : Int => i+1
        case d : Double if d < 0.0 => d-0.1 // double형
        case d : Double => d+0.1
        case text : String => text + "s" // string형
    }
}

print문을 출력하면 아래와 같습니다.

println(use_match(1)) // int
println(use_match(0.1)) // double
println(use_match("ABCD")) // string

title

   

6. 케이스 클래스
  • 손쉽게 내용을 클래스에 저장하고, 그에 따라 매치하고 싶은 경우에 사용한다.

    new 를 사용하지않고 케이스 클래스의 인스턴스 생성이 가능하다.

case class Calculator(brand: String, model: String) // Scala class를 새로 만들때 case class 선택
def c_type(calc: Calculator) = calc match {
    case Calculator("HP", "20b") => "financial"
    case Calculator("HP", "48g") => "scientific"
    case Calculator("HP", "30b") => "business"
    case Calculator(_, _) => "Calculator of unknown type"
}
// Example 1
val hp20b = Calculator("HP", "20b")
val hp20B = Calculator("HP", "20b")
println(hp20b==hp20B) // 두 생성자의 인자가 같으면 true, 다르면 false
// Example 2
val hp30b = Calculator("HP", "30b")
println(c_type(hp20b))
println(c_type(hp30b))

Example 1과 2의 출력은 아래와 같습니다.

title