Home > OS >  How can I implement a method that change directly the value this with dart extension?
How can I implement a method that change directly the value this with dart extension?

Time:09-28

I want to know how can I change/affect the value of this with dart extensions without returning a value.

For example, when I do this :

"example text".cutFirstLetter();

by just executing it, I want its String value for the rest of the code to be "e", I don't want it to be returned in function, I want the whole of it to change.

let me more explain :

extension ExmapleExtension on String {
    String cutFirstLetter() {
        return this.substring(0, 1);
    }
}

this will work only as returned value, so it will work on places that expect the return such as print("example text".cutFirstLetter()); or if I assigned to another String such as String newExampleText = "example text".cutFirstLetter();

I want when I just call it in a line, it will execute it on the this referred String

I tried something like:

extension ExmapleExtension on String {
    removeTletter() {
        this = this.substring(0, 1);
    }
}

but it throws an error.

CodePudding user response:

First, strings are immutable. Perhaps you've noticed there are no methods in the String class that change the value of the string "in-place". They all return values (often other Strings).

Second, you cannot assign to this, only call methods on it.

So you'll have to be happy with just returning a new value.

  •  Tags:  
  • dart
  • Related