Pablo
10/02/2020, 11:54 AMclass Dog(val name: String, val age: Int, val owner:Owner = Owner.Jhon)
Then I have another class that creates that Dog as :
fun getOwner() : Owner {
return if (something is true) Owner.Peter else Owner.Jhon
}
And this is what I'd like to improve, I see that I have this Owner.Jhon
duplicated, because is default value already is there any way to avoid this Owner.Jhon from getOwner?spand
10/02/2020, 12:00 PMStephan Schroeder
10/02/2020, 1:49 PMgetOwner
only contains a single expression, so you should do the single-line version:
fun getOwner() : Owner = if (something is true) Owner.Peter else Owner.Jhon
you can even drop the : Owner
return-type if you want.
Another thing is that I normally don’t see Java-type getSomething
functions since you can define a more koliny dynamic something
-property:
val owner: Owner
get() = if (something is true) Owner.Peter else Owner.Jhon
if the value is only initialized once, you could of course change it to a traditional property:
val owner: Owner = if (something is true) Owner.Peter else Owner.Jhon
.
getOwner
isn’t a method of Dog
, is it? Because you can already access the owner property of dog directly (since it’s not private).
val dogOwner = dog.owner