In: Computer Science
anwer in kotlin
fun main() {
val text = "Kotlin".getFirstAndLast()
val firstChar = text["first"]
val lastChar = text["last"]
// TODO 2
println()
}
// TODO 1
fun String.getFirstAndLast() = mapOf<String, Char>()
TODO 1:
Make the getFirstAndLast function the extension of the String class
with the return type Map <String, Char>
TODO 2:
Add functions to print the values of the firstChar and lastChar
variables in the console.
there no more information from this task
i dont know.
this is the full task
The question is complete and correct. To solve the question, the following two tasks have to be carried out in Kotlin:
1. To complete the function getFirstAndLast() which when invoked on a string, returns a map. This map has two strings (first and last) as the key which correspond to the first and last characters of the string on which the function is called. Note that the function is called using a string object ("Kotlin").
2. Once we receive the map, the next task is to show the results by printing them to the console. If the first part is done, then for the second part requires only two print statements.
The code to solve the complete question is below. This has been tested on online Kotlin compiler. If there is difficulty in executing this code then reinstalling Kotlin on your machine can solve the problem.
fun main() {
//Here the function getFirstAndLast() is called on String object
"Kotlin"
val text = "Kotlin".getFirstAndLast()
//The following two statements extract the first and last character
from the returned map (text)
val firstChar = text["first"]
val lastChar = text["last"]
//This solves second part by printing first and last characters on
console
println(firstChar)
println(lastChar)
}
//This function is the solution of the first part
fun String.getFirstAndLast(): Map<String, Char>{
//this keyword refers to the currently calling object. String in
our case.
//len stores the length of the string
val len = this.length
//In this statement we create a map which is the solution
val map = mapOf("first" to this.get(0), "last" to
this.get(len-1))
//Finally the map is returned
return map
}