Strings and Pairs
Kotlin is an object-oriented language, and almost everything piece of data we use in our programs is an object. This means that as well as encapsulating some data, they provide a set of methods, which are functions that act on that data.
Syntax reminder:
We create objects by calling constructors. These look like regular function calls, but match the name of the type being constructed. Strings are objects, and we often create a string just by using a string literal. We call methods and access properties by using dot notation. A method call ends with a pair of parentheses, but a property access does not.
// string literal
val string = "hello world"
// constructing a pair
val p = Pair(3, "C")
// property access
val l = string.length
val n = p.first
// method call
val uc = string.uppercase()
Try the following:
Write a boolean function snap()
that determines whether a pair of Strings contains two matching elements:
import org.junit.Assert
import org.junit.Test
class TestSnap() {
@Test fun matching() {
Assert.assertTrue(snap(Pair("a", "a")))
}
@Test fun matchingMixedCase() {
Assert.assertTrue(snap(Pair("a", "A")))
}
@Test fun notMatching() {
Assert.assertFalse(snap(Pair("a", "b")))
}
@Test fun emptyStringsMatch() {
Assert.assertTrue(snap(Pair("", "")))
}
}
//sampleStart
fun snap() = TODO()
//sampleEnd
Write a boolean function isPalindrome()
that determines whether a given string is palindromic (have a look at the methods available on Strings):
import org.junit.Assert
import org.junit.Test
class TestPalindromes() {
@Test
fun allAs() {
Assert.assertTrue(isPalindrome("aaaaaa"))
}
@Test
fun palindrome() {
Assert.assertTrue(isPalindrome("madamimadam"))
}
@Test
fun notPalindrome() {
Assert.assertFalse(isPalindrome("abcdef"))
}
}
//sampleStart
fun isPalindrome() = TODO()
//sampleEnd