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

Including return type in return value  RSS feed

 
Ben Charles
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I'm currently working through some examples in a book and came across the following method:



I can't find a reason why the author included the return type (double) in the value to be returned since double is already the return type, and the method works with or without it. The mpg variable is of type int, so is this just changing the type of both miles and mpg to double before division occurs?

Thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66203
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cast has a higher precedence than division, so the cast is for the numerator, not the result.

 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If one (or both) of the variables weren't cast to double, integer division would occur. So if mile = 1 and mpg = 2, without the cast fuelneeded() would return 0;
 
Ben Charles
Greenhorn
Posts: 9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Understood. Thanks for the replies Knute and Bear!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!