Solution: Extension Methods

Solution for extension method challenge.

Solution: Extension Methods

In this lesson, you will explore the solution to the “Extension Methods” challenge.

Solution #1

The first challenge is to implement the convertMileToKm() extension method. This method converts the mile(s) to the kilometer(s). Since we know 1 mile is equivalent to 1.6 kilometers, we need to multiply the given mile with 1.6 to calculate the kilometer equivalent.

this refers to the object the extension method is called upon. The object is passed implicitly.

  double convertMileToKm() => this * 1.6; 

Solution #2

The second part of the challenge is to call convertMileToKm() on the double mile value and print its kilometers equivalent.

  double kms = mile.convertMileToKm();

Try the code snippet below to evaluate the code altogether.

Get hands-on with 1400+ tech skills courses.