他の関数が引数で取る機能が高階関数として知られ、ここではその一例です:
// 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
クラスは3つのクラスメンバーを持ち、そのうちの2つは変数であり、その1つは関数です。あなたは抽象クラスを拡張した場合、あなたが値を試すことができます:
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"
になります。
変更しようとしているいくつかの値のためになるクラスのメンバのための機能を利用するためのより良い例:「DEF」に使用されている理由
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
。パラメータはnothingまたはvalまたはvarでなければなりません。パラメータで "def"とは何ですか? – Jason
どこにもパラメータが表示されず、引数も表示されません。あなたの質問を明確にすることはできますか? –
ああ、私は@Jasonがクラスのメンバーとクラスのパラメータを混ぜていると思う! – pedrofurla