Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does this method works without a return statement outside while loop?  RSS feed

 
Varuna Seneviratna
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does this method works without a return statement outside while loop?

/**
* Returns "yes", "no", or "maybe" randomly
*
*/
public String getResponse()
{
int response=0;
while(true)
{
response=randomNumberGenerator.nextInt(3);

if(response==0)
return "No";
else if(response == 1)
return "Yes";
else
return "May be";
}
}

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the compiler is smart enough to understand that that the line before the last bracket will never be reached.
 
Varuna Seneviratna
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When placing return statements inside methods what is the theory to follow?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to return a value from any possible path. If the compiler finds a path where a value is not returned, it will result in a compiler error. This kind of error is automatically signaled by IDEs like Eclipse or IntelliJ.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!