2013-08-26 21 views
10

Trong mã dưới đây, tôi nhận được lỗi này:Lỗi: lớp Thú cần phải được trừu tượng, vì: nó có 5 thành viên chưa thực hiện

class Animal needs to be abstract, since: it has 5 unimplemented members. /** As seen from class Animal, the 
missing signatures are as follows. * For convenience, these are usable as stub implementations. */ def 
favFood_=(x$1: Double): Unit = ??? def flyingType_=(x$1: scala.designpatterns.Strategy.Flys): Unit = ??? def 
name_=(x$1: String): Unit = ??? def sound_=(x$1: String): Unit = ??? def speed_=(x$1: Double): Unit = ??? 

Nếu tôi khởi tạo tất cả các biến thể hiện của lớp Thú tới _ sau đó mã biên dịch chính xác. Lỗi này có nghĩa là gì?

package scala.designpatterns 

/** 
* 
* Decoupling 
* Encapsulating the concept or behaviour that varies, in this case the ability to fly 
* 
* Composition 
* Instead of inheriting an ability through inheritence the class is composed with objects with the right abilit built in 
* Composition allows to change the capabilites of objects at runtime 
*/ 
object Strategy { 

    def main(args: Array[String]) { 

    var sparky = new Dog 
    var tweety = new Bird 

    println("Dog : " + sparky.tryToFly) 
    println("Bird : " + tweety.tryToFly) 
    } 

    trait Flys { 
    def fly: String 
    } 

    class ItFlys extends Flys { 

    def fly: String = { 
     "Flying High" 
    } 
    } 

    class CantFly extends Flys { 

    def fly: String = { 
     "I can't fly" 
    } 
    } 

    class Animal { 

    var name: String 
    var sound: String 
    var speed: Double 
    var favFood: Double 
    var flyingType: Flys 

    def tryToFly: String = { 
     this.flyingType.fly 
    } 

    def setFlyingAbility(newFlyType: Flys) = { 
     flyingType = newFlyType 
    } 

    def setSound(newSound: String) = { 
     sound = newSound 
    } 

    def setSpeed(newSpeed: Double) = { 
     speed = newSpeed 
    } 

    } 

    class Dog extends Animal { 

    def digHole = { 
     println("Dug a hole!") 
    } 

    setSound("Bark") 

    //Sets the fly trait polymorphically 
    flyingType = new CantFly 

    } 

    class Bird extends Animal { 

    setSound("Tweet") 

    //Sets the fly trait polymorphically 
    flyingType = new ItFlys 
    } 

} 

Trả lời

23

Bạn phải khởi tạo biến. Nếu bạn không, Scala giả sử bạn đang viết một lớp trừu tượng và một lớp con sẽ điền vào khởi tạo. (Trình biên dịch sẽ cho bạn biết như vậy nếu bạn chỉ có một biến uninitialized duy nhất.)

Viết = _ làm cho Scala điền vào các giá trị mặc định.

Vấn đề là làm cho bạn suy nghĩ về những gì sẽ xảy ra khi ai đó (ví dụ: sau khi bạn quên rằng trước tiên bạn cần đặt thứ) gọi điều gì đó sử dụng ví dụ: âm thanh mà không có nó đã được thiết lập.

(Nói chung, bạn nên suy nghĩ cẩn thận xem đây có phải là cách phù hợp để cấu trúc mã của bạn hay không; không cần bất kỳ cơ chế nào để thực thi khởi tạo, đang yêu cầu sự cố.)

Các vấn đề liên quan