Skip to content

Commit 41ce086

Browse files
Merge pull request eugenp#3173 from sazzer/master
Pull Request for BAEL-807
2 parents ab40539 + f00c95f commit 41ce086

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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("<", "&lt;")
13+
.replace(">", "&gt;")
14+
}
15+
16+
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
17+
Assert.assertEquals("&lt;Tag&gt;", "<Tag>".escapeForXml())
18+
Assert.assertEquals("a&amp;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

Comments
 (0)