Scala abstract class, what does it do?

I am studying abstract classes, this link is very informative.

scala general method override

abstract class Foo[T] { self:T => def bar1(f:T):Boolean def bar2(f:T):T } class FooImpl extends Foo[FooImpl]{ override def bar1(f:FooImpl) = true override def bar2(f:FooImpl) = f } 

What does self mean: T means? T is a class parameter, as I understand it.

+6
source share
1 answer

As @cchantp noted in his comment, self : T in this case is an annotation of type self , basically saying that the instance of Foo[T] should also behave like T You can see that this is indeed the case in FooImpl , like FooImpl <: Foo .

You can learn more about self-type annotations here , here or here . Note that in most cases you will see that it is used in the context of Injection Dependency and Pattern Cake.

The most interesting of the second link , I think the initial section is:

In other words, what is the meaning of this:

trait A
trait B { this: A => }

when you could just do this:

trait A
trait B extends A

Why should you use [this syntax]?

[...] the answer usually comes down to "B requiring A" (annotations), and "B is A" (inheritance), and that the first is better for dependency management.

Finally, and just for clarification, we note that the word self is not required at all. It can be any valid variable name, but self or this most often a convention. That is, you can do:

 trait A trait B { myVar: A => } 

but it will be less common.

+3
source

Source: https://habr.com/ru/post/1014423/


All Articles