Merge pull request #6649 from kacperkoza/BAEL

extension function in java
This commit is contained in:
Loredana Crusoveanu 2019-04-08 00:01:49 +03:00 committed by GitHub
commit 8424a1047e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 7 deletions

View File

@ -0,0 +1,9 @@
@file:JvmName("Strings")
package com.baeldung.kotlin
fun String.escapeForXml() : String {
return this
.replace("&", "&")
.replace("<", "&lt;")
.replace(">", "&gt;")
}

View File

@ -0,0 +1,30 @@
package com.baeldung.kotlin;
import kotlin.text.StringsKt;
import org.junit.Assert;
import org.junit.Test;
import static com.baeldung.kotlin.Strings.*;
public class StringUtilTest {
@Test
public void shouldEscapeXmlTagsInString() {
String xml = "<a>hi</a>";
String escapedXml = escapeForXml(xml);
Assert.assertEquals("&lt;a&gt;hi&lt;/a&gt;", escapedXml);
}
@Test
public void callingBuiltInKotlinExtensionMethod() {
String name = "john";
String capitalizedName = StringsKt.capitalize(name);
Assert.assertEquals("John", capitalizedName);
}
}

View File

@ -6,13 +6,6 @@ import org.junit.Test
class ExtensionMethods {
@Test
fun simpleExtensionMethod() {
fun String.escapeForXml() : String {
return this
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
}
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
Assert.assertEquals("&lt;Tag&gt;", "<Tag>".escapeForXml())
Assert.assertEquals("a&amp;b", "a&b".escapeForXml())