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 ?
There are at least two questions here:
class Child extend Parentvs.class Child(a: Parent)andclass MyClassvs.implicit class MyClass.Regarding the 1st question, this is the difference between inheritance and composition
Prefer composition over inheritance?
In
class Child(a: Parent),Childhas access to public members ofParentbutChildis not aParent. Inclass Child extend Parent,Childadditionally has access to protected members ofParentandChildis aParent.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 MyClasslikeval 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 likeparent.foo(). You can't addfoodirectly to a class if this is a third-party class.