Kotlin for C# Developers

2.2. Extension methods

These are used much the same as in C# but are declared differently. In Kotlin:

C#

public static class StringExtensions
{
    public static string MaskPassword(this string password)
    {
        return new string('*', password.Length);
    }
}

Kotlin

fun String.maskPassword(): String {
    return "*".repeat(this.length)
}

Because there’s no need for a this method parameter, we can also have extension properties in Kotlin

Kotlin

val String.masked: String
    get() = "*".repeat(length)   // Note, as in C# 'this' can be omitted

Next: Classes