Pascal How
03/06/2018, 10:54 AMtoast(...)
without worrying about show()
etc
My issue is whether this is actually a form of abuse on the extension function mechanism because Toast is not really an extension of context.
Similarly, I have come across several examples where extension functions have been used to simply shave off a parameter from the original method call. Any opinions?miszmaniac
03/06/2018, 11:02 AMPascal How
03/06/2018, 11:06 AMmiszmaniac
03/06/2018, 11:07 AMPascal How
03/06/2018, 11:07 AMleosan
03/06/2018, 11:16 AMContext
itself being required for everything… but since we have this god object, makes sense these extensions for this contextmiszmaniac
03/06/2018, 11:16 AMgildor
03/06/2018, 11:17 AMPascal How
03/06/2018, 11:23 AMfun Context.loadImageCenterCrop(url: String, imageView: ImageView) {
Picasso.withContext(this)
.load(url)
.centerCrop()
.fit()
.into(imageView)
}
// Elsewhere
context.loadImageCenterCrop("<http://example.com/image.jpg>", myImageView)
miszmaniac
03/06/2018, 11:26 AMleosan
03/06/2018, 11:26 AMPascal How
03/06/2018, 11:26 AMfun ImageView.loadImageCenterCrop(url: String) {
Picasso.withContext(this.getContext())
.load(url)
.centerCrop()
.fit()
.into(this)
}
leosan
03/06/2018, 11:27 AMtoast
would be weird making an extension of String
miszmaniac
03/06/2018, 11:27 AMfun ImageView.picassoLoad(url: String, callback: ((requestCreator: RequestCreator) -> Unit)? = null) {
this.context.picasso.load(url).apply {
callback?.invoke(this)
}.into(this)
}
julioyg
03/06/2018, 1:50 PMmiszmaniac
03/06/2018, 1:51 PMPascal How
03/06/2018, 1:55 PMfun Context.loadImageCenterCrop(url: String, imageView: ImageView) {
Picasso.withContext(this)
.load(url)
.centerCrop()
.fit()
.into(imageView)
}
// Elsewhere
context.loadImageCenterCrop("<http://example.com/image.jpg>", myImageView)
and
fun ImageView.loadImageCenterCrop(url: String) {
Picasso.withContext(this.getContext())
.load(url)
.centerCrop()
.fit()
.into(this)
}
both make your code more concise and both use the extension function mechanism, the first approach is bad because context has nothing to do with loadImageCenterCrop
miszmaniac
03/06/2018, 2:02 PMval Context.picasso: Picasso
get() = Picasso.with(this)
Context works as service locator anyway, so no harm done here:)gildor
03/06/2018, 2:04 PMmiszmaniac
03/06/2018, 2:17 PMgildor
03/07/2018, 1:03 AMMakoto
03/07/2018, 4:24 AMtoast("Hi there!")
toast(R.string.message)
longToast("Wow, such duration")
Pascal How
03/07/2018, 10:09 AMToast
it is fine to extend Context
because it is like bringing new additions to the scope and it is convenient but in the case of
fun Context.loadImageCenterCrop(url: String, imageView: ImageView) {
Picasso.withContext(this)
.load(url)
.centerCrop()
.fit()
.into(imageView)
}
Even though essentially, it is doing the same thing as extending Context
with Toast
, it is not fine because it is better to extend ImageView
?gildor
03/07/2018, 10:27 AM