2017-01-29 5 views
2

스칼라에서 유지 mixin과 오류, 나는이 세 개의 파일이 있습니다난 그냥 스칼라을 배우고

abstract class Animal() { 
    name 
    sound 
} 



class Dog(n : String) extends Animal { 
    name = n 
    val sound = "Boof" 
} 

trait Speaking extends Animal { 
    def speak(n : String, s : Sound) : String = { 
     println(s + "! I'm " + n + "!") 
    } 
} 

내 주요 방법은을, 나는 다음과 같은 코드가 있습니다

d = new Dog("Maddie") with Speaking 
println(d.speak) 

내가 실행 이 코드는 오류가 발생했습니다 : 찾을 수 없음 : 값 d

답변

2

val 앞에 d을 넣기 전에 선언하십시오.

abstract class Animal() { 
    def name: String // You need a type(String) and a qualifier(def) 
    def sound: String // the same 
} 

class Dog(n : String) extends Animal { 
    // Type is not obligatory here, as it is inherited from Animal. 
    // But you still need a qualifier(val) 
    val name = n 
    val sound = "Boof" 
} 

trait Speaking extends Animal { 
    // This method doesn't need those params, 
    // since this trait extends Animal, 
    // so it has access to name and sound defined there. 
    def speak: String = { 
    sound + "! I'm " + name + "!" 
    } 
} 

귀하의 주요 방법은 동일하게 유지 :

0

는 나는 이런 식으로 뭔가해야한다고 생각합니다.