Reputation: 31
I did try this but i get to Error's.
fun main() {
val addExclamationMark: (String) -> String = {if it.contains("!") -> it else -> it + "!"}
println(addExclamationMark("Hallo Welt"))
}
Type mismatch: inferred type is Unit but String was expected Expecting a condition in parentheses '(...)' Unexpected tokens (use ';' to separate expressions on the same line)
Can you please tell me how to do this right with some explanation so i understand Kotlin more ? ;)
Upvotes: 0
Views: 717
Reputation: 15668
Error Type mismatch: inferred type is Unit but String was expected
is because you defined the return datatype as String, but you didn't return anything. Two reasons for that:
Putting all together, this works:
fun main() {
val addExclamationMark: (String) -> String = { if (it.contains("!")) it else it + "!"}
println(addExclamationMark("Hallo Welt"))
}
Upvotes: 1
Reputation: 6572
String
and returns a String
import java.util.*
fun main() {
// Lambda with String -> String
val addExclamationMarkConst: (String) -> String = { if (it.contains("!")) it else "$it!" }
println(addExclamationMarkConst("Hallo Welt"))
// Method that implements the function with String -> Unit
Optional.of("Hallo Welt").ifPresent(::printExclamationMark)
}
fun printExclamationMark(input: String): Unit {
val elementToPrint: String = if (input.contains("!")) input else "$input!"
println(elementToPrint)
}
Upvotes: 0
Reputation: 778
You have to pass a string, didn't return anything,
fun main() {
Val addExclamationMark: (String) -> String = {
if (it.contains("!")) {
it
} else {
"$it!"
}
}
println(addExclamationMark("Hallo Welt"))
}
Upvotes: 0