Scala (10): Implicit class

What is “implicit class”?

In fact, I don’t know and also couldn’t explain what it is. Don’t be afraid. We can use example to help us to find the final answer.

First we see this example as below.

implicit class Person(val name: String) {
  def sayHello = "hello " + name
}
"world".sayHello // output: "hello world"

So we know that when the string “world” wants to call the function: sayHello, and finds that “world” doesn’t have this method. And then “world” tries to transfer to another type which has sayHello method. Here “world” finds that there is an implicit class which can transfer to Person class. Finally, “world” calls it and is to be a Person class and call the sayHello method.

implicit class mush attach a primary constructor parameter. The benefit of this requirement is that you can merge two steps together, one is to create a class, the other is to build a implicit method to get the instance of this class.

What is primary constructor?

In Scala, it is quite simply to get primary constructor. The part which follows the keyword: class, is the primary constructor. (see another post to know detailed information about constructor)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s