英文:
How extend a class is diff from implicit class?
问题
我正在努力理解子类(class Child extends Parent
)和隐式类(implicit class Child(a: Parent)
)之间的区别。在这两种情况下,子实例都能够访问父类和子类的方法。我是否漏掉了什么或者理解有误?有人能帮我纠正一下我的理解吗?
英文:
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 ?
答案1
得分: 4
以下是翻译的内容:
有至少两个问题在这里:
class Child extend Parent
与class Child(a: Parent)
之间的区别是什么,class MyClass
与implicit class MyClass
之间的区别是什么。
关于第一个问题,这涉及到继承和组合之间的区别。
在 class Child(a: Parent)
中,Child
可以访问 Parent
的公共成员,但 Child
不是 Parent
。而在 class Child extend Parent
中,Child
不仅可以访问 Parent
的公共成员,还可以访问受保护的成员,同时 Child
是 Parent
。
关于第二个问题,你可以像这样实例化 class MyClass
:val x: MyClass = new MyClass
。你也可以实例化隐式类,但通常你不会这样做。隐式类的实例化是由编译器完成的。隐式类的主构造函数变成了隐式转换。这对于添加扩展方法很方便。
你不能扩展一个 final 类,但可以通过组合或隐式类来使用它。通过组合,你需要像 new Child(parent).foo()
这样访问方法,而使用隐式类时,你可以像直接访问一样访问它们,例如 parent.foo()
。如果这是一个第三方类,你不能直接将 foo
添加到类中。
英文:
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
https://stackoverflow.com/questions/49002/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
.
https://stackoverflow.com/questions/11343840/favor-composition-over-inheritance
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.
https://stackoverflow.com/questions/10375633/understanding-implicit-in-scala
https://stackoverflow.com/questions/65844327/understand-scala-implicit-classes
https://stackoverflow.com/questions/8524878/implicit-conversion-vs-type-class
https://stackoverflow.com/questions/75458954/how-to-write-an-implicit-numeric-for-a-tuple
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论