this keyword in dart when combined with $ operator returns unexpected, wierd output

68 Views Asked by At

So I am writing a program for my reference about the usage of this keyword. I declared a class variable, let's say 'x=1', in a class "Example". I declared a method inside that class, "method1". Inside that method as well, I declared another variable with name 'x=5' again. My intention is, without using this keyword, the ouput should be 5, i.e., local variable value. But when I use this keyword, the output will be 1, because it refers to the class variable. The code looks like This.

class Example{
 int x=1
 ;

 void method1()
 {
  int x=5;
  print(x); 
  print(this.x);
 }

}

This was working correctly as I expected. The problem arises when I tried to combine the code with the $ operator.

So I rewrote the code in this way for better reference

class Example{
 int x=1;
 
 void method1()
 {
  int x=5;
  print("I am $x"); 
  print("I am $this.x");
 }

}

This is where the problem arises. The first line of code prints the value correctly as "I am 5". But the next line, instead of printing "I am 1", prints something like this

"I am Instance of 'Example'.x"

Unexpected Ouput

I have no Idea what this means, I am new to Object Oriented Programming and dart. Is this throwing some exception? What the compiler is trying to say? Is this some wierd interaction between the this keyword and $ operator? And Most importantly, how to rectify it? Thanks in advance.

1

There are 1 best solutions below

0
Dhafin Rayhan On

In Dart, to use string interpolation where the expression is not an identifier, use ${expression}.

print("I am $x"); // "x" is an identifier
print("I am ${this.x}"); // "this.x" is not an identifier

See: String interpolation

To put the value of an expression inside a string, use ${expression}. If the expression is an identifier, you can omit the {}.