<https://kotlinlang.org/docs/reference/extensions....
# android
y
Do I just create a new kt file like this?
Copy code
package foo.bar

fun Baz.goo(){ ... }
👍 2
Oh okay, so I create a file called extensions and ooooooooh. Okay okay, this is good.
If you add
@file:JvmName("SomeExtensionFile")
you will be able to call from Java as well (if your codebase is mixed)
y
@bachhuberdesign Is that your repo?
b
Yep, just a selection of extensions that I use for personal projects
y
lmao look at my resize extension, it's the exact same as yours:
Copy code
fun Bitmap.resize(image: Bitmap, maxWidth: Int = 1920, maxHeight: Int = 1080): Bitmap {
    if (maxHeight > 0 && maxWidth > 0) {
        val width = image.getWidth()
        val height = image.getHeight()
        val ratioBitmap = width.toFloat() / height.toFloat()
        val  ratioMax = maxWidth.toFloat() / maxHeight.toFloat()
        var finalWidth = maxWidth
        var  finalHeight = maxHeight

        if (ratioMax > ratioBitmap) {
            finalWidth = (maxHeight.toFloat() * ratioBitmap).toInt()
        } else {
            finalHeight = (maxWidth.toFloat() / ratioBitmap).toInt()
        }
        var finalimage = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true)
        return finalimage
    } else {
        return image
    }
}
b
Nice, thank you StackOverflow 😂
y
I steal a solid 20% of my code, no worries.
StackOverflow is like MIT license anyways. Right? 😉
b
I'm hoping eventually the Android team at Google releases an "official" extension library so I don't need to drop this or Anko into my projects
y
Am I supposed to only use extensions on objects themselves? It's a shame I can't Bitmap.resize()
Looks like I can only call myBitmap.resize()
b
If you wanted to call it like that, you could just write a static method and pass in your Bitmap
instead of extension
y
I didn't think kotlin had static methods, just companion objects.
b
You can use @JvmStatic annotation
If you use that annotation it needs to be inside a companion object or top level object though
y
Yeah I'm looking it up now. Never used the annotation tags tbh
So I'd have to pass the static method when I declare the bitmap or?
b
I mainly use it for Fragment instances i.e.
Copy code
companion object {
        @JvmStatic
        fun newInstance(someInt: Int): SomeFragment {
            val fragment = SomeFragment()

            val bundle = Bundle()
            bundle.putInt(SOME_KEY, someInt)
            fragment.arguments = bundle

            return fragment
        }
    }
What do you mean?
If you wanted static you could do
Copy code
object BitmapHelper {
    
    @JvmStatic
    fun createScaledBitmap(): Bitmap {
        // TODO: 
    }
    
}
and then call BitmapHelper.createScaledBitmap()
Extension is probably cleaner though
y
I guess extensions work for now.