Reputation: 13
fun main(args: Array<String>) {
CustomerData.count = 98
CustomerData.typeOfCustomers()
println(CustomerData.count)
}
object CustomerData {
var count: Int = -1
fun typeOfCustomers(){
println("This came from typeOfCustomers function in CustomerData class")
}
}
This prints "This came from typeOfCustomers function in CustomerData class" to console. But, when I use return instead of println() that line doesn't return to console like below code
fun main(args: Array<String>) {
CustomerData.count = 98
CustomerData.typeOfCustomers()
println(CustomerData.count)
}
object CustomerData {
var count: Int = -1
fun typeOfCustomers():String{
return "This came from typeOfCustomers function in CustomerData class"
}
}
Upvotes: 0
Views: 200
Reputation: 18577
Both your examples call CustomerData.typeOfCustomers()
.
In the first example, that call writes the string directly to the console, which is why you see it.
In the second example, the call returns the string but does nothing with it, so the string is simply discarded.
Like most modern languages, in Kotlin the result of a function/method call is a value, and a value is always a valid statement; the value will simply be ignored unless you do something with it.
If you instead used that value in a println()
call:
println(CustomerData.typeOfCustomers())
…then you'd see your string on the console as expected. Or you could assign the result to a variable:
val type = CustomerData.typeOfCustomers()
Or use it in an expression:
val message = "Call returned: " + CustomerData.typeOfCustomers()
Or call one of its methods, or use it in any other way.
Otherwise, Kotlin will make the call but simply ignore the result.
Upvotes: 0
Reputation: 1708
Return just returns an object from the function. In your case, the object returned is a String. To print the string you would need to do this:
val typeOfCustomer = CustomerData.typeOfCustomers()
println("${CustomerData.count} $typeOfCustomer")
Upvotes: 3