Would somebody please help me understand what is h...
# getting-started
n
Would somebody please help me understand what is happening with a function declaration like the following?
fun foo(): String = "bar"
What I understand is that function foo takes no parameters and has a return type of String. What is odd to me coming from other languages where I have never seen this, is that it is valid for there to be no body declaration but just an equal sign after the return type assigning the return value as a constant. If you could, would you please provide a use case for a function declared similarly?
s
An example that comes to mind is for a concrete implementation of a method defined in an interface e.g.
Copy code
interface MyInterface {
  fun foo(): String
}

class MyClass: MyInterface {
  override fun foo() = "bar"
}
c
It’s just syntax sugar. It uses the right-hand-side of the
=
as the body of the function, but can infer the return type of that function based on that expression.
It’s quite handy for implementing interfaces with static values as Stephen pointed out, and also nice for “wrapping” functions without having to indent the whole thing. For example, making a test method work with coroutines becomes quite nice:
Copy code
@Test
fun test() {
    // getResult() is not suspending
    expectThat(getResult()).isEqualTo("some value")
}

@Test
fun testMySuspendingFunction() = runBlocking<Unit> {
    // someone made getResult() suspending? No worries, just add runBlocking to the test method signature for a clean diff!
    expectThat(getResult()).isEqualTo("some value")
}
n
So it makes a little more sense now for sure. I think the most confusing thing is that we're defining a return type, but never using the return keyword. If
=
is supposed to be the function body, it'd essentially be:
Copy code
fun foo(): String { 
"bar"
 }
Which doesn't make any sense because a "return" is never used and "bar" isn't assigned to anything. This would throw an error in a language like java. I guess by assigning the value to the return type, I should just imagine that Kotlin just infers the return is the value assigned to the return type
s
no, if you want to write it all out, it would be:
Copy code
fun foo(): String {
   return "bar"
 }
n
Thanks Stephan and Casey for the examples. I appreciate the responses 🙂
c
Think of the
=
more in the mathematical sense, or in a functional programming sense. It is not saying that
foo()
has or returns the value of the expression. It is saying that
foo()
is equivalent to the expression, and any call to that function can effectively be replaced by the expression
👍 2
💡 1
n
Very well put Casey. That's a great way to remember this
🙇‍♂️ 1