Is there any Kotlinian way to : ```class Dog(val ...
# announcements
p
Is there any Kotlinian way to :
Copy code
class Dog(val name: String, val age: Int, val owner:Owner = Owner.Jhon)
Then I have another class that creates that Dog as :
Copy code
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?
s
You can extract default owner to companion object and use it both places
s
You write Then I have another class that creates that Dog as : but what follows is a function that creates an Owner, so I’m a bit confused. What I can say is that
getOwner
only contains a single expression, so you should do the single-line version:
Copy code
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:
Copy code
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:
Copy code
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).
Copy code
val dogOwner = dog.owner