언어별 선택적 매개변수

Jmnote (토론 | 기여)님의 2018년 8월 28일 (화) 01:14 판 (→‎Ruby)

1 개요

언어별 optional arguments
언어별 optional parameters
언어별 default parameters
언어별 선택적 매개변수

2 Java

메소드 오버로딩 활용
public class MyClass {
    static void makeCoffee() {
        makeCoffee("아메리카노");
    }
    static void makeCoffee(String type) {
        System.out.println(type + " 한잔");
    }
    public static void main(String args[]) {
        makeCoffee();
        makeCoffee("카푸치노");
		// 아메리카노 한잔
		// 카푸치노 한잔
    }
}
null 입력
public class MyClass {
    static void makeCoffee(String type) {
        if(type==null) type="아메리카노";
        System.out.println(type + " 한잔");
    }
    public static void main(String args[]) {
        makeCoffee(null);
        makeCoffee("카푸치노");
        // 아메리카노 한잔
        // 카푸치노 한잔
    }
}

3 JavaScript

undefined 처리
function multiply(a, b) {
  var b = b || 1;
  return a*b;
}
console.log( multiply(5) ); // 5
function multiply(a, b) {
  if (b === undefined) b = 1;
  return a*b;
}
console.log( multiply(5) ); // 5
function multiply(a, b) {
  var b = (typeof b !== 'undefined') ?  b : 1;
  return a*b;
}
console.log( multiply(5) ); // 5
ES6
function multiply(a, b = 1) {
  return a*b;
}
console.log( multiply(5) ); // 5

4 PHP

function makecoffee($type = '아메리카노') {
    echo "$type 한 잔\n";
}
makecoffee();
makecoffee('카푸치노');
// 아메리카노 한 잔
// 카푸치노 한 잔

5 Python

def makeCoffee(t = '아메리카노'):
    print( t + ' 한 잔' )

makeCoffee()
makeCoffee('카푸치노')
# 아메리카노 한 잔
# 카푸치노 한 잔
def showUrl( host, port=80 ):
    print( 'http://' + host + ':' + str(port) )
 
showUrl('jmnote.com')
showUrl('google.com', 443)
# http://jmnote.com:80
# http://google.com:443

6 Ruby

def makeCoffee(type='아메리카노')
    print type, " 한 잔\n"
end
makeCoffee()
makeCoffee('카푸치노')
# 아메리카노 한 잔
# 카푸치노 한 잔

7 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}