抽象类Scala。教程和匿名类中的错误

时间:2018-05-22 00:19:40

标签: scala

我正在阅读此博客文章here

我跟着我和我的Scala工作表一直在大吼我说方法没有正确定义:

这有效:

abstract class Pet {
    var age: Int = 0
    val hello: String
    val greeting: String = s"I like to play with you!"
    def sayHello: Unit = { println(hello) }
    override def toString = s"$hello, $greeting"
}

但这不是:

abstract class Pet {
    var age: Int = 0
    val hello: String
    val greeting: String = s"I like to play with you!"
    def sayHello: = { println(hello) }
    override def toString = s"$hello, $greeting"
}

错误只是说wrong type

为什么这不起作用?到底是怎么回事?博客文章错了吗?

println(new Pet {
    val hello = "Meow2"
})

它返回:

Meow2, I like to play with you!
res5: Unit = ()

你能实例化抽象类吗?我正在阅读Odersky的书,他在哪里使用这种语法?似乎没有在任何地方提到过。

1 个答案:

答案 0 :(得分:4)

语法错误在这里:

def sayHello: = { println(hello) }

:之后必须有一个类型。你可以这样做:

def sayHello: Unit = { println(hello) }

或者你可以这样做:

def sayHello = { println(hello) }

在后一个选项中,推断出类型。

对于抽象类,不,你不能实例化它们。从技术上讲,该示例中发生的事情是声明该抽象类的匿名子类,并实例化该抽象类。这两个几乎是一样的:

println(new Pet {
    val hello = "Meow2"
})


class Cat2 extends Pet {
    val hello = "Meow2"
}
println(new Cat2)
相关问题