Novoa
04/23/2019, 11:15 PMfun 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?stephan_marshay
04/23/2019, 11:27 PMinterface MyInterface {
fun foo(): String
}
class MyClass: MyInterface {
override fun foo() = "bar"
}
Casey Brooks
04/23/2019, 11:32 PM=
as the body of the function, but can infer the return type of that function based on that expression.@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")
}
Novoa
04/23/2019, 11:41 PM=
is supposed to be the function body, it'd essentially be:
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 typestephan_marshay
04/23/2019, 11:42 PMfun foo(): String {
return "bar"
}
Novoa
04/23/2019, 11:43 PMCasey Brooks
04/23/2019, 11:43 PM=
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 expressionNovoa
04/23/2019, 11:44 PM