我们可以在类定义中将方法作为参数吗?

时间:2017-04-01 00:40:51

标签: scala

以下是我通过scala书进行的代码片段。 Car类的一个参数是" def color:String"

我不明白。 " DEF"是定义方法的关键字。怎么能在参数中使用?

scala> abstract class Car {
 |   val year: Int
 |   val automatic: Boolean = true
 |   def color: String
 | }

1 个答案:

答案 0 :(得分:0)

将其他函数作为参数的函数称为高阶函数,下面是一个示例:

// A function that takes a list of Ints, and a function that takes an Int and returns a boolean.
def filterList(list: List[Int], filter: (Int) => Boolean) = { /* implementation */ }

// You might call it like this
def filter(i: Int) = i > 0
val list = List(-5, 0, 5, 10)
filterList(list, filter)

// Or shorthand like this
val list = List(-5, 0, 5, 10)
filterList(list, _ > 0)

然而,这不是您的示例中发生的事情。在您的示例中,Car类有三个类成员,其中两个是变量,其中一个是函数。如果要扩展抽象类,可以测试值:

abstract class Car {
  val year: Int
  val automatic: Boolean = true
  def color: String
}

case class Sedan(year: Int) extends Car {
  def color = "red"
}

val volkswagen = Sedan(2012)
volkswagen.year       // 2012
volkswagen.automatic  // true
volkswagen.color      // red

在这里,将颜色作为一个函数(使用def)并没有多大意义,因为在我的实现中,颜色总是"red"

为类成员使用函数的一个更好的例子是某些值将会改变:

class BrokenClock {
  val currentTime = DateTime.now()
}

class Clock {
  def currentTime = DateTime.now()
}

// This would always print the same time, because it is a value that was computed once when you create a new instance of BrokenClock
val brokenClock = BrokenClock()
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00

// This will be a different value every time, because each time we are calling a function that is computing a new value for us
val clock = Clock()
clock.currentTime // 2017-03-31 22:51:00
clock.currentTime // 2017-03-31 22:52:00
clock.currentTime // 2017-03-31 22:53:00