0

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 ? ;)

1
  • Where did you get that using arrows for if flow control was a valid syntax? Is this some new experimental feature? Commented Jan 25, 2023 at 12:56

3 Answers 3

1

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 -> in the condition 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")) } 

Check here

Sign up to request clarification or add additional context in comments.

Comments

0

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")) } 

Comments

0
  • You can use a lambda that take a String and returns a String
  • 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) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.