함수 정의 def 예제

scala 2016. 4. 22. 17:40

 ($: scala line interpreter 라고 치고.....)


기본 def:

$def h(x:String):Type = { println(x)}


1. 한 줄 일때는 curly brace 생략 가능

$def  h() = println("hi")

$def  h = println("hi")    (이것도 동일 동작.)


  => 이 때 아무동작 안하는 듯한 return type은 Unit이라고 부름 (java 의 void 와 비슷)


2. retrurn Type은 보통 안 붙여도 자동추론 하지만. recursive일 때는 꼭 필요.




3. def this     :    추가 생성자용도이다.   (overloaded constructor or Auxilary constructor 라고 부른다) 

   primary 생성자는 자동생성되므로..아래 예제처럼 추가 생성자를 생성할때  this함수와 함께 사용할 수 있다.

   

 class Test( msg:String, count:Int) {


    def this (msg:String ) = this (msg,1)


 }    


Posted by yongary
,