
Learn about extension functions. Then implement the extension functions Int.r() and Pair.r() and make them convert Int and Pair to a RationalNumber.
Pair is a class defined in the standard library:
data class Pair<out A, out B>(
val first: A,
val second: B
)
fun Int.r(): RationalNumber = TODO()
fun Pair<Int, Int>.r(): RationalNumber = TODO()
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = RationalNumber(this,1)
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second)
data class RationalNumber(val numerator: Int, val denominator: Int)
확장함수를 구현하여 Int 및 Pair를 RationalNumber(유리수)로 변환하는 문제이다.
유리수는 분모가 0이 아닌 모든 분수형식으로 나타낼 수 있는 수이다. 분모로 1이 들어갈 수 있기 때문에 모든 정수는 유리수이다.
Int는 정수이므로 분자에는 this를 넣어주고 분모에는 1을 넣어 주었다.
Pair는 2개의 숫자를 받아오기 때문에 첫번째와 두번째 수를 RaitionalNumber의 매개변수로 순서대로 넣어주었다.
this는 클래스의 인스턴스를 참조하는데 사용된다.this를 사용하여 클래스 내부에서 멤버 변수나 멤버 함수를 참조할 수 있다.위의 문제를 예를 들어서 설명한다면 5.r()을 호출하면 this는 5가 된다.