How to customize the getter in Kotlin?

Asked

Viewed 335 times

8

When we create a variable of type val, in the case of Java, only the getter relative to it. Different when a type variable is created var, in which the getter and setter. See below for 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 a customization of getter in Java, for example using the toUpperCase so that the result returns in "high box" when it comes to a string:

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

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

  • 1

    I improved my answer. I thought it was important to warn you =D

  • 1

    Who denied the question could at least explain the reason why I can edit it and try to collaborate more with our community.

2 answers

9

For this code apparently:

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

I put in the Github for future reference.

Obviously I made a stter also just to demonstrate already that he has a field. It’s better than in C#, and much better than in Java which doesn’t even have its own mechanism.

Of course you can do the same as Java and it 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".

  • 3

    It will be hard to lose the habit of putting ;

  • 1

    @I’m glad the guys already thought about it and left the ; optional. = D

  • It’s true :))))

9


It’s a bit like.

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

His class, in Kotlin, could be written like this:

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

Complete code for testing

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.

Browser other questions tagged

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