Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I implement a method that change directly the value this with dart extension

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading