Pallavi
11/10/2019, 3:48 PMdoSomething
?
//Way 1 (doSomething is a member function)
data class A(val item: String) {
fun doSomething(): String{
return item.toUpperCase()
}
}
//Way 2 (making doSomething an extension function)
data class A(val item: String)
fun A.doSomething(): String {
return item.toUpperCase()
}
Mark Murphy
11/10/2019, 3:53 PMthis
has a toUpperCase()
function defined somewhere. Should your extension function have return item.toUpperCase()
?Pallavi
11/10/2019, 3:54 PMMark Murphy
11/10/2019, 4:03 PMA
is really a Customer
class, and you have some presenter / controller / viewmodel that needs to gather data from a Customer
and prepare it for a UI or other presentation. It might be that the code "feels better" if Customer
has certain behaviors, but that those behaviors are not general purpose ones, but are limited to the UI logic. You might implement those Customer
behaviors as private extension functions in the viewmodel file, so the viewmodel can have the nicer syntax but those functions cannot be used elsewhere.
However, this is all solely my opinion, and I expect that there are multiple patterns that other developers use. And, of course, if A
is not your own class, but is one from a library, then extension functions are much more common, given that you cannot directly modify A
.Adam Powell
11/10/2019, 4:19 PMAdam Powell
11/10/2019, 4:23 PMAdam Powell
11/10/2019, 4:23 PMPallavi
11/10/2019, 4:35 PMPallavi
11/10/2019, 7:56 PMkarelpeeters
11/11/2019, 12:29 AMAdam Powell
11/11/2019, 1:08 AMRainer Schlonvoigt
11/03/2020, 12:20 PMRainer Schlonvoigt
11/03/2020, 12:22 PM