|
| 1 | +package com.baeldung.kotlin |
| 2 | + |
| 3 | +import org.junit.Assert |
| 4 | +import org.junit.Test |
| 5 | + |
| 6 | +class ExtensionMethods { |
| 7 | + @Test |
| 8 | + fun simpleExtensionMethod() { |
| 9 | + fun String.escapeForXml() : String { |
| 10 | + return this |
| 11 | + .replace("&", "&") |
| 12 | + .replace("<", "<") |
| 13 | + .replace(">", ">") |
| 14 | + } |
| 15 | + |
| 16 | + Assert.assertEquals("Nothing", "Nothing".escapeForXml()) |
| 17 | + Assert.assertEquals("<Tag>", "<Tag>".escapeForXml()) |
| 18 | + Assert.assertEquals("a&b", "a&b".escapeForXml()) |
| 19 | + } |
| 20 | + |
| 21 | + @Test |
| 22 | + fun genericExtensionMethod() { |
| 23 | + fun <T> T.concatAsString(b: T) : String { |
| 24 | + return this.toString() + b.toString() |
| 25 | + } |
| 26 | + |
| 27 | + Assert.assertEquals("12", "1".concatAsString("2")) |
| 28 | + Assert.assertEquals("12", 1.concatAsString(2)) |
| 29 | + // This doesn't compile |
| 30 | + // Assert.assertEquals("12", 1.concatAsString(2.0)) |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + fun infixExtensionMethod() { |
| 35 | + infix fun Number.toPowerOf(exponent: Number): Double { |
| 36 | + return Math.pow(this.toDouble(), exponent.toDouble()) |
| 37 | + } |
| 38 | + |
| 39 | + Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1) |
| 40 | + Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1) |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + fun operatorExtensionMethod() { |
| 45 | + operator fun List<Int>.times(by: Int): List<Int> { |
| 46 | + return this.map { it * by } |
| 47 | + } |
| 48 | + |
| 49 | + Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2) |
| 50 | + } |
| 51 | +} |
0 commit comments