3

I can define a "big" function using a "small" function:

fun apply3(a:Int, b:Int, c:Int, func: (Int,Int,Int)->Int ): Int{
    return func(a,b,c)
}

I can call it so:

println(apply3(1,2,3,{a,b,c->a+b+c}))

On the other hand, if I want to use the same function several times and use a name for it, I have problems:

val plus1: (Int,Int,Int)->Int = {a,b,c->a+b+c}  //this is OK
...
fun plus2(a:Int, b:Int, c:Int)=a+b+c    // this too
...
println(apply3(1,2,3,plus1))    // this is allowed
...
println(apply3(1,2,3,plus2))    // this is NOT allowed

The last line is forbidden. With message:

Type mismatch
Required: (Int,Int,Int)->Int
Found: Int

Why? For me, plus2 and plus2 are the same things?

This post has an answer that advises to use ::plus2 in my case. This helps technically but does not explain the difference between these two functions.

Gangnus
  • 24,044
  • 16
  • 90
  • 149
  • This error message is misleading and clearly broken – voddan Dec 22 '17 at 06:59
  • 1
    Reported https://youtrack.jetbrains.com/issue/KT-21966 – voddan Dec 22 '17 at 07:15
  • @voddan Please, look here: https://stackoverflow.com/questions/47934397/can-i-use-a-name-of-the-lambda-as-the-parameter-passed-outside-of-parentheses/47934608?noredirect=1#comment82846149_47934608. I think, that is even worse problem. – Gangnus Dec 22 '17 at 10:31
  • @Gangnus I have. What's the problem? How can I help? – voddan Dec 22 '17 at 10:35
  • @voddan I have understood, Daniil, that you are an active person in the Kotlin community? A break in the substitution law should be covered at least by some explanation. – Gangnus Dec 22 '17 at 10:39
  • Syntax rules of many programming languages generally do NOT comply with the substitution law in one way or another. So IMO this case is no big deal and I am satisfied with how the docs explain this case. – voddan Dec 22 '17 at 12:01
  • @Gangnus If you feel the documentation needs additional clarifications, please submit PR to https://github.com/JetBrains/kotlin-web-site. The team is usually very fast to review them and merge. – voddan Dec 22 '17 at 12:04

1 Answers1

4

You need to use a function reference:

println(apply3(1,2,3,::plus2))
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Sorry, you yourself had made me to change the question so that your answer is not the answer anymore. But it was an answer for me and it did help. Merry Christmas and Happy New Year for you. Please, don't take offence, I am a more theoretical person than you obviously. :-) – Gangnus Dec 22 '17 at 12:19
  • @Gangnus - No problem :) – Oliver Charlesworth Dec 22 '17 at 12:32