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 ? ;)
CodePudding user response:
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:
- the -> are not necessary, they are too much
- the condition has to be in parentheses
Putting all together, this works:
fun main() {
val addExclamationMark: (String) -> String = { if (it.contains("!")) it else it "!"}
println(addExclamationMark("Hallo Welt"))
}
CodePudding user response:
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"))
}
CodePudding user response:
- You can use a lambda that take a
String
and returns aString
- In some situation, you can also use a method that implements a function by inference. The method have to respect the signature of the function.
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)
}