본문 바로가기

Scala

[Play Framework2] Action composition PlayFramework에서는 Action이 뭔가 Restful 통신을 할때 반응하는 객체로 쓰여진다... 이번에는 이 Action을 활용하는 방법을 알아보자 자세한 사항은 : https://www.playframework.com/documentation/2.3.x/ScalaActionsComposition object LoggingAction extends ActionBuilder[Request] { def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { Logger.info("Calling action") block(request) } }위와 같이LoggingAction을 만들고def index = Loggi.. 더보기
[Play Framework2] Setting and discarding cookies Cookie를 사용하는 방법이다. (https://www.playframework.com/documentation/2.3.x/ScalaResults) val result = Ok("Hello world").withCookies( Cookie("theme", "blue"))Setval result2 = result.discardingCookies(DiscardingCookie("theme"))Discardingval result3 = result.withCookies(Cookie("theme", "blue")).discardingCookies(DiscardingCookie("skin"))Set & Discarding def home(name:String) = Action {request=> val prev.. 더보기
[Play Framework2] Http Routing 프로젝트 파일에서 Conf 폴더에 routes 라는 파일이 있다. 이 파일에서 모든 url을 관리하는 듯하다. (#은 주석이다.)GET /clients/all controllers.Clients.list()GET /clients/:id controllers.Clients.show(id: Long)GET /files/*name controllers.Application.download(name)(*id 표현은 GET /files/images/logo.png 와 같이 파일형식의 파라미터를 받을수있다.) GET /items/$id controllers.Items.show(id: Long)($id 로 정규화 표현을 받을 수 있다.) # Extract the page parameter from the path, .. 더보기
[Scala] Local Type Inference 스칼라는 Java랑 다르게 알아서 타입을 추론이 가능하다~!!!! 하지만 막무가내로 되는게 아니라 조금은 안정하게??설계를 한듯하다. 하나씩 예시를 살펴보자~! 첫번째 예시는 코드로 파악이 가능하다. object InferenceTest1 extends App { val x = 1 + 2 * 3 // the type of x is Int val y = x.toString() // the type of y is String def succ(x: Int) = x + 1 // method succ returns Int values} 두번째 예시는 함수에 리턴타입을 정의하지 않았다. 그리고 재귀호출이라서 컴파일에서 오류를 발생시킨다. object InferenceTest2 { def fac(n: Int) = i.. 더보기
[Scala] Explicitly Typed Self References 자기 자신을 다른 Type으로 선언이 가능하다. 예시를 보자 Graph라는 클래스와 abstract class Graph { type Edge type Node def connectWith(node: Node): Edge = { val edge = newEdge(this, node) // now legal edges = edge :: edges edge } } ...} 더보기
[Scala] Lower Type Bounds 아래의 예시를 보면 LinkedList를 구현하였다. 하지만 ListNode[String]이라고 선언하면 ListNode[Object]를 사용할 수 없게 되는 상황이 나온다. case class ListNode[T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t def prepend(elem: T): ListNode[T] = ListNode(elem, this)} 조금 더 규칙을 허술하게 하고 싶을때 ?? 사용하면 좋다. prepend 함수에 [U >: T] 라고 해주면 case class ListNode[+T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t de.. 더보기
[Scala] Upper Type Bounds 스칼라는 추상타입의 경계를 조정? 이 가능하다. 예시로 보자 아래의 코드를 보면 T 더보기
[Scala] Traits 스칼라에서는 JAVA에서 interface와 비슷한 Traits가 있다. 하지만 구현이 가능한 것이 약간 다르다. trait Similarity { def isSimilar(x: Any): Boolean def isNotSimilar(x: Any): Boolean = !isSimilar(x)} 이렇게 trait을 선언하고 아래와 같이 사용해 보자 class Point(xc: Int, yc: Int) extends Similarity { var x: Int = xc var y: Int = yc def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x&& obj.asInstanceOf[Point].y == y}obj.. 더보기
[Scala] Polymorphic Methods 스칼라에서는 다형성 메소드를 지원한다. 아주 간단하게 사용 할 수 있다. 아래의 예시 코드를 보자 object PolyTest extends App { def dup[T](x: T, n: Int): List[T] = if (n == 0) Nil else x :: dup(x, n - 1) println(dup[Int](3, 4)) println(dup("three", 3))} dup라는 함수가 있고 [T]로 선언이 되어지게 되면 다형성이 적용이 된다. 출력 결과는 다음과 같다.List(3, 3, 3, 3)List(three, three, three) 더보기
[Scala] Pattern Matching 다른 언어에서 Switch와 Case문을 Scala에서는 간편하게 match라는 키워드로 구현하면 된다. 우선은 Int를 사용하는 예제를 보자 object MatchTest1 extends App { def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "many" } println(matchTest(3))} 두번째 예제는 Any라는 키워드를 통해 다양한 키워드 매칭이 가능하다. 그리고 또 놀라운 점은case y : 보자 case에 매칭되지 않는 Int 타입인 경우 y라는 변수로 활용이 가능하다. object MatchTest2 extends App { def matchTest(x: Any): Any = x .. 더보기