What could be a good way for provide a compile tim...
# announcements
d
What could be a good way for provide a compile time - type safety on
Any
? Let’s say that I got this class and I want the better way for ensure that
image
is
Drawable, Int, Bitmap, File, String or Uri
and placeholder is
Drawable, Int, Bitmap or File
without crashing at runtime
l
The only way to be safe on type is to use the correct type
I don't think there's any sort of structure to guarantee what you want
Perhaps with annotation processing
d
So I should go for some “extra route” like lint or annotation processor, right?
s
What about creating a sealed class for this (eg ImageResource), where each of its subclasses is wrapping either a Drawablenor an Int, ...or a Uri? Instead of Any?, you would use ImageResource?.
👍 2
d
I guess this is the most easy-typesafe solution, but I would like to avoid the wrapping. Something like
androidx.annotation.DrawableRes
would be great
l
What is the issue with wrapping?
I think the main point here is that you're trying to escape the type system a little bit, and I don't really understood why
d
This
Copy code
imageLoader {
    image = item.image
    placeHolder = item.imagePlaceHolder
    target = tvChannelImage
}
would become this:
Copy code
imageLoader {
    image = ImageResource( item.image )
    placeHolder = ImageResource( item.imagePlaceHolder )
    target = tvChannelImage
}
which I don’t like 🙂
you’re trying to escape the type system a little bit, and I don’t really understood why
Who don’t like to break the rules? 😄
g
Wrapping has another advantage: it can accept params. If your drawable is an
Int
, let say a vector drawable that needs to be of different color, then you need to provide a color filter, along the
Int
.
for what it's worth, you can have extension functions in these types (with annotated receiver maybe):
item.image.toRes()
d
In that case I would prefer to have
imageDrawable
,
imageBitmap
, etc and add some boilerplate to the Builder
p
Well you can just use a function instead of a property and overload it with all types
t
If the only issue you have with wrapping is the readability of the DSL syntax, you can define extension properties on your builder, so that there is a property for each supported type :
Copy code
inline var Builder.imageDrawableRes: Int
    get() = throw Exception("No getter here")
    set(value) = this.image = DrawableResource(value)
You can then use it in the DSL like this :
Copy code
imageLoader {
    imageDrawableRes = R.drawable.my_awesome_image
}
d
@tseisel yes thanks, I tough at something like that a couple of messages above 👍