I wonder if return is used among the phrases that return the Cotlin value.

Asked 2 years ago, Updated 2 years ago, 116 views

Hello, I'm a beginner who just started studying programming.

I'm currently studying Cotlin with the goal of developing an app. (I'm studying with Kang's Kotlin programming book.)

As I studied, I think return should be used at the end of this phrase, but there is a part where return is used and some parts do not use return, so I am asking you a question.

1. fun some():Int { return 10 }

2. fun myfun(x1 : Int, x2 : Int) : Boolean { return x1>x2 }

3. val sum3 = { x1 : Int, x2 : Int -> println("call sum3()..") x1+x2 }

4. if(a>0) "hello" else "world"

I brought some of the examples in the book that I don't understand, but I don't know why because it seems like they're returning all the values, but some of them use return and others don't use return.

And return comes out when you search for a return statement, but I don't even know what to search for a phrase that doesn't have a return.

I would appreciate it if you could tell me what the difference is between using and not using return.

kotlin return

2022-09-20 16:33

1 Answers

If you look at your code, return is used only for the first and second codes. Return literally means return and the commonality of codes 1 and 2 is both fun. If you explain the code below in order

fun some(): Int {//1:Declared//3: Called without argument
    Return 10 //4:10
}
fun main() {
    Call the print(some())//2:some function. //5: Print the return value (10)
}

This is the case if there is no factor and there is a return value, and if there is a factor and a return value,

funmyfun(x1: Int, x2: Int): Boolean {//1: Declared//3: Called after receiving two integers as arguments
    return x1 > x2//4:x1 returns True if x2 or False.
}
fun main(){
    print(myfun(5, 3))//2:5 and 3 are used as factors to call the myfun function.//5: Outputs True, which is the return value
}

The bottom line is that return is only available when there is a function. Reference


2022-09-20 16:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.