How to create extension methods in Kotlin

Asked

Viewed 62 times

1

Hello, I’m coming from C# to work with Kotlin and C# when there was any code that was used constantly, it was common to create extension methods that worked as shortcuts to it. Ex:

namespace Test
{
    public static class Test 
    {
        public static string PutDotInEndOfString(this string str) 
        {
            return str + ".";
        }
    }
}

Because of this facility, I am looking for something to (or replace or declare a new function) that can facilitate the use of simple methods like toLowerCase that currently presents me a Warning over the Locale default, ex:

class Test {
    private lateinit var str: String
    init {
        str = "TEST"
    }
    testMethod(): String {
        // return str.toLowerCase() // assim fica aparecendo o warning
        return str.toLowerCase(Locale.getDefault())
    }
}

Is there any way I can extend or overwrite the method toLowerCase in the example above so you don’t have to pass the locale every time you use it?

1 answer

3


Yes, there is a feature very similar to C#. You just need to prefix the function name with the type that will receive the extension method.

You can see more about this on documentation.

fun String.myToLowerCase(): String {
    return this.toLowerCase(Locale.getDefault())
}

print("KOTLIN IS AWESOME".myToLowerCase())

See working

  • 2

    ... face I was thinking it was something otherworldly (after all Kotlin has java under the cloths)... ta increasingly cool moves with koltin rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.