title: Function definition: fun vs val
body: <p>I'm curious about what is the suggested way to define member functions in Kotlin. Consider these two member functions:</p>
  
  <pre><code>class A {
  
    fun f(x: Int) = 42
  
    val g = fun(x: Int) = 42
  
  }
  </code></pre>
  
  <p>These appear to accomplish the same thing, but I found subtle differences.</p>
  
  <p>The <code>val</code> based definition, for instance, seems to be more flexible in some scenarios. That is, I could not work out a straight forward way to compose <code>f</code> with other functions, but I could with <code>g</code>. To toy around with these definitions, I used the <a href="https://github.com/MarioAriasC/funKTionale">funKTionale</a> library. I found that this does not compile:</p>
  
  <pre><code>val z = g andThen A::f // f is a member function
  </code></pre>
  
  <p>But if <code>f</code> were defined as a <code>val</code> pointing to the same function, it would compile just fine. To figure out what was going on I asked IntelliJ to explicitly define the type of <code>::f</code> and <code>g</code> for me, and it gives me this:</p>
  
  <pre><code>val fref: KFunction1&lt;Int, Int&gt; = ::f
  
  val gref: (Int) -&gt; Int = g
  </code></pre>
  
  <p>So one is of type <code>KFunction1&lt;Int, Int&gt;</code>, the other is of type <code>(Int) -&gt; Int</code>. It's easy to see that both represent functions of type <code>Int -&gt; Int</code>.</p>
  
  <p>What is the difference between these two types, and in which cases does it matter? I noticed that for top-level functions, I can compose them fine using either definition, but in order to make the aforementioned composition compile, I had to write it like so:</p>
  
  <pre><code>val z = g andThen A::f.partially1(this)
  </code></pre>
  
  <p>i.e. I had to partially apply it to <code>this</code> first.</p>
  
  <p>Since I don't have to go through this hassle when using <code>val</code>s for functions, is there a reason why I should ever define non-Unit member functions using <code>fun</code>? Is there a difference in performance or semantics that I am missing?</p>