Scala: self type annotation

↘锁芯ラ 提交于 2019-12-14 04:06:41

问题


(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.



来源:https://stackoverflow.com/questions/19821827/scala-self-type-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!