0

I'm trying to understand the difference between child class (class child extend Parent) and implicit class ( implicit class Child (a: Parent))

In both cases, the child instance is able to access both Parent and child methods. Am I missing something or wrong ?

Can anyone please help me to correct my understanding ?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Lenny
  • 83
  • 1
  • 1
  • 11

1 Answers1

4

There are at least two questions here:

  • what is the difference class Child extend Parent vs. class Child(a: Parent) and
  • what is the difference class MyClass vs. implicit class MyClass.

Regarding the 1st question, this is the difference between inheritance and composition

Prefer composition over inheritance?

In class Child(a: Parent), Child has access to public members of Parent but Child is not a Parent. In class Child extend Parent, Child additionally has access to protected members of Parent and Child is a Parent.

What is the difference between "IS -A" relationship and "HAS-A" relationship in Java?

Favor composition over inheritance

What is the Difference between inheritance and delegation in java

Regarding the 2nd question, you can instantiate class MyClass like val x: MyClass = new MyClass. You can instantiate implicit class too but normally you never do. It's the compiler that instantiates the implicit class. The primary constructor of implicit class becomes an implicit conversion. This is convenient to add extension methods.

Understanding implicit in Scala

Understand Scala Implicit classes

Implicit conversion vs. type class

How to write an implicit Numeric for a tuple

How to add extension method to a singleton object in scala 2?

You can't extend a final class but can use it via composition or implicit class. With composition you'll have to access methods like new Child(parent).foo(), with implicit class you can access them as if this were direct access like parent.foo(). You can't add foo directly to a class if this is a third-party class.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66