How to customize the getter in Kotlin?

7

When we create a variable of type val , in the case of Java, only getter is created in relation to it. Different when a variable of type var is created, in which getter and setter is created. Here is an example:

Kotlin using val :

class Article construtor(content: String){
    val content: String = content
}

Equivalence in Java :

public class Article {

    private String content;

    public final String getContent() {
        return this.content;
    }

    public Article(String content) {
        this.content = content;
    }
}

See below for a custom customization of getter in Java, using for example the toUpperCase method so that the result returns in the "uppercase" when it is a string :

public final String getContent() {
   return this.content.toUpperCase();
}

Following this concept, what would be the best way to customize getter in Kotlin?

    
asked by anonymous 10.08.2017 / 15:43

2 answers

8

It's a bit similar.

In Kotlin, classes can not have fields ( fields ), that is, they can only have properties. But to our delight, the language has a mechanism of backing field implicit (called field ) for when you need to use custom access modes.

Your class in Kotlin could be written like this:

class Article(content: String) {
    var content: String = content
        get() = field.toUpperCase()
}

Complete test code

fun main(args: Array<String>) {
    var art = Article("Alguma coisa")
    println(art.content)
    art.content = "outra coisa"
    println(art.content)
}

class Article(content: String) {
    var content: String = content
        get() = field.toUpperCase()
}

See working here.

    
10.08.2017 / 15:49
8

For this code apparently:

var content: String
    get() = this.content.toUpperCase();
    set(value) {
        if (value != "") {
            field = value
        }
    }

Obviously I made a stter also just to demonstrate since it has a field . It is better than in C #, and much better than in Java that does not even have its own mechanism.

Of course you can do the same as Java and can be useful if you use some library that requires this form. This is one of the problems that if using a platform with "history".

    
10.08.2017 / 15:48