Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returns and Inlines

Tags:

java

kotlin

I am trying to find the Kotlin equivalent to this Java return:

return new int[] {1, 2, 3};

I've tried just declaring then returning like this:

val returnArr: IntArray = intArrayOf(1, 2, 3)
return returnArr

But I get a warning that says "Variable used only in following return and can be inlined". What exactly is meant by inline? Is there a way to do this all on one line?

like image 583
Kevin Patrick Avatar asked Jan 03 '23 20:01

Kevin Patrick


1 Answers

In the context of the warning, "inlining" means removing local variables, parameters, functions, etc. that really don't need to be there, and the code would be simpler without them. For example, in the statement

val returnArr: IntArray = intArrayOf(1, 2, 3)
return returnArr

returnArr serves no purpose (except perhaps when debugging), and you could replace it with

return intArrayOf(1, 2, 3)

The use of the term "inlining" to refer to such simplifications is a JetBrains convention, I think, due to the existence of the "Inline" refactoring that can automate simplifications like the one we're talking about (right-click on returnArr and select Refactor/Inline).

The warning is not a compiler warning; it is one of many style inspections that IntelliJ does. If you like your temporary variables, I think you can disable it by going to Preferences/Editor/Inspections/Kotlin/Redundant Constructs and unchecking "Unnecessary local variable".

like image 120
Hank D Avatar answered Jan 05 '23 09:01

Hank D