2017-11-29 10 views
0
abstract class Bar[M] { 
    def print(t: M): Unit = { 
    println(s"Bar: ${t.getClass()}") 
    } 
} 

trait Foo[M] { 
    this: Bar[M] => 
    def print2(t: M): Unit = { 
    println(s"Foo: ${t.getClass()}") 
    } 
} 

object ConcreteBar extends Bar[Int] with Foo[Int] {} 
object ConcreteFooBar extends Bar[Int] with Foo[Int] {} 

object Test { 
    def main(args: Array[String]): Unit = { 
    ConcreteBar.print(1) 
    ConcreteFooBar.print2(1) 
    } 

위 예제에서 자체 타이핑 한 "막대"특성에서 유형을 반복 할 필요가없는 방법이 있습니까? 따라서 우리는 다음과 같이 ConcreteFooBar를 선언 할 수 :스칼라 자체 유형 및 제너릭 클래스

object ConcreteFooBar extends Bar[Int] with Foo {} 

답변

0

당신은 Foo 대신 유형 매개 변수의 추상적 인 형식을 사용할 수 있습니다, 다음과 같이 :

abstract class Bar[M] { 
    type Base = M 
    def print(t: M): Unit = { 
    println(s"Bar: ${t.getClass()}") 
    } 
} 

trait Foo { 
    type Base 
    def print2(t: Base): Unit = { 
    println(s"Foo: ${t.getClass()}") 
    } 
}