-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExtensionFunctions.kt
34 lines (23 loc) · 1.05 KB
/
ExtensionFunctions.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package i_introduction._8_Extension_Functions.StringExtensions
import util.TODO
fun String.lastChar() = this[this.length() - 1]
//'this' can be omitted
fun String.lastChar1() = this[length() - 1]
fun use() {
// Try IntelliJ's Ctrl+Space "default completion" after the dot: lastChar() will be visible in
// the completion window and can be easily found
"abc".lastChar()
}
// 'lastChar' compiles to a static function in the class StringExtensionsPackage
// and can be used in Java with a String as its first argument (see JavaCode8.useExtension)
fun todoTask8(): Nothing = TODO(
"""
Task 8.
Implement the extension functions Int.r(), Pair<Int, Int>.r()
to support the following manner of creating rational numbers:
1.r(), Pair(1, 2).r()
""",
references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) })
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = RationalNumber(this, 1)
fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(this.first, this.second)