2014-03-26 3 views
4

나는 케이크 패턴을 가지고 놀았으며 완전히 이해하지 못하는 것이 있습니다.케이크 패턴 : 특성을 혼합하기

주어진 다음의 공통 코드 :

trait AServiceComponent { 
    this: ARepositoryComponent => 
} 

trait ARepositoryComponent {} 

을 혼합 다음과 같은 방법이

trait Controller { 
    this: AServiceComponent => 
} 

object Controller extends 
    Controller with 
    AServiceComponent with 
    ARepositoryComponent 

작동하지만 다음과 같은 오류와

trait Controller extends AServiceComponent {} 

object Controller extends 
    Controller with 
    ARepositoryComponent 

하지 않습니다

우리는 그들이 모든 서브 클래스에 공통 될 것이라고 알고 있다면 10

우리가 "푸시"계층 구조에 종속 수 없습니다 하는가? Controller만큼이 이러한 문제를 해결하지 않고 인스턴스화 아니에요으로, 종속성을 가질 수 있도록

컴파일러는 허용하지할까요?

답변

3

여기에 같은 문제로 실행하는 약간 간단한 방법 :

scala> trait Foo 
defined trait Foo 

scala> trait Bar { this: Foo => } 
defined trait Bar 

scala> trait Baz extends Bar 
<console>:9: error: illegal inheritance; 
self-type Baz does not conform to Bar's selftype Bar with Foo 
     trait Baz extends Bar 
         ^

문제는 컴파일러는 당신이 하위 유형 정의에 자기 형 제약 조건을 반복 할 것으로 예상한다는 것입니다. 당신은 단지 다음과 같이 변경해야 당신에

trait Baz extends Bar { this: Foo => } 

을 : 내 단순화 경우에 우리가 쓸 것

trait Controller extends AServiceComponent { this: ARepositoryComponent => } 

이 요구 사항을 만들어 어떤 의미 - 그것은 할 수 Controller를 사용하여 사람을 원하는 것이 합리적이다 상속받는 유형을 보지 않고이 종속성에 대해 알아야합니다.

+0

예, 나는 그것이 암시 적 또는 명시 적 일들이 코드에 있어야하는 방법에 대한 설계 문제의 결국 같아요. 믹스 인의 의존성을 재발 명하는 것은 다소 반복적으로 느껴지 겠지만, 특히 그것이 특성에 직접적으로 사용되지 않는다면. –