Scala: self type annotation

2019-09-11 18:14发布

问题:

(Trying to understand the use of self types by probing the borders.)

This cannot be instantiated (D and String are classes, but one of them has to be mixed in. plus String is final.). But is there any other use for it?

class D { 
    foo: String => 
    def f2 = foo.substring(1) 
}

Update: Sorry, I seem to be not good at asking questions. What I want to know is whether this strange special case makes sense. The case where class D can never be instantiated, as 1. I cannot mix in String, as it is not a tarit. 2. I cannot mix in D, as .. 3. I cannot extend String, as it is final.

回答1:

The self type annotation generally has two purposes:

  1. Enforce a certain base class/trait and ensure that your class or trait can only be inherited by or mixed into that type, and
  2. Reference an exterior case when implementing an inner case. (If it wasn't for this syntax, what would 'this' refer to?)

I'm not sure I understand your example or the reasoning behind it. Elaborate?



回答2:

trait Table
trait Desert
trait Meal

class Pancake extends Desert
class Spaghetti extends Meal
class Woodentable extends Table

suppose you want to make sure an existing Class mixes in those dependencies you use:

trait Restaurant {
self: Table with Desert with Meal =>
def foo():Unit ...
}

Now every class (or trait) that mixes in Restaurant has to provide the following dependencies. This is used in the cake pattern for instance. If any of these dependencies are not present the compiler will complain at compile time.