s-hunter
s-hunter

Reputation: 25816

How to set default lambda function for named lambda argument with generics in Kotlin?

This code prints "Hello 1". parseInput have two generic types, the first arg is a simple object of the first generic type A, the second arg is a function which suppose to change the generic type A to generic B. As you can see it works fine in the following.

fun toGreeting(input : Int) : String {
    return "hello " + input
}

fun <A, B> parseInput(raw : A, toB : (raw : A) -> B) : B {
    return toB(raw)
}

fun main(args: Array<String>) {
    val greeting = parseInput(1, ::toGreeting)
    println(greeting)
}

The question is how can I give a default lambda value for the second named argument in the parseInput. So I can call this function by just providing the first argument, and having it to use the default lambda function.

val greeting = parseInput(1)
println(greeting)

Upvotes: 1

Views: 225

Answers (1)

yole
yole

Reputation: 97148

Your requirements are contradictory. You want to be able to specify a function that returns a value of type B for any B (which is actually impossible by itself; the only possible such function is a function that always throws an exception), and you also want the compiler to be able to infer what B is when you haven't given the compiler any information from which it can be determined. In your example:

 val greeting = parseInput(1)  
 println(greeting)

...there is zero information from which the compiler could determine what type the greeting variable needs to have. There is no logic that would substitute Unit or any other specific type in this case; instead, as you correctly remark in your comment, this code fails to compile.

If you want greeting to be Unit in this case, you can achieve this by simply overloading the function:

fun <A> parseInput(raw: A) {
}

This function will return Unit, giving you the exact behavior you're looking for.

Upvotes: 1

Related Questions