2016-09-27 117 views
1

目前我正在學習Scala使用教程,和我所遇到的語法我不明白(我的天堂沒有找到答案):斯卡拉功能語法

object Demo { 
    def main(args: Array[String]) { 
    println(apply(layout, 10)) 
    } 

    def apply(f: Int => String, v: Int) = f(v) 

    def layout[A](x: A) = "[" + x.toString() + "]" 
} 

def layout[A](x: A) = "[" + x.toString() + "]" 

我不明白布局之後和參數聲明之前的[A]。

它是返回類型嗎?

對我來說,scala中函數的一般語法如下:

def functionName ([list of parameters]) : [return type] = { 
    function body 
    return [expr] 
} 

回答

4

A是所謂的類型參數。類型參數允許您爲任何A編寫一種方法。可能是AInt,Double,或者甚至是你寫的自定義類。由於所有這些都有一個從Any繼承的toString方法,這將起作用。

例如,當我們這樣做:

println(layout(1L)) 
println(layout(1f)) 

這是相同的文字:

println(layout[Long](1L)) 
println(layout[Float](1f)) 

類型參數明確地傳遞。

+0

如果你知道Java中,這大約相當於他們如何詮釋與''泛型方法。 – Thilo

+0

在這種情況下,它有什麼用處嗎?爲什麼不只是'def layout(x:Any)'? – Thilo

+1

@Thilo在這個特別的例子中,這並不太有意義。人們可以使用「Any」來實現相同的目標。當你寫一個接受類型參數的方法時,你通常擁有可重用的代碼,你可以在編譯時保存類型信息。 –

0
def layout[A](x: A) = "[" + x.toString() + "]" 

[A]這裏是類型參數。此函數定義允許您爲此類型參數提供任何類型作爲參數。

// If you wanted to use an Int 
layout[Int](5) 

// If you wanted to use a String 
layout[String]("OMG") 

// If you wanted to one of your classes 
case class AwesomeClass(i: Int, s: String) 

layout[AwesomeClass](AwesomeClass(5, "omg")) 

也...在該方法中def layout[A](x: A) = "[" + x.toString() + "]",它被指定的功能參數xtype A,Scala中可以使用該信息來推斷從函數參數x類型參數。

所以你其實並不需要提供type argument使用該方法時,所以實際上你可以像下面的不太詳細地寫在上面的代碼,

// As we provided `i : Int` as argument `x`, 
// Scala will infer that type `A` is `Int` in this call 
val i: Int = 5 
layout(i) 

// Scala will infer that type `A` is `String` in this call 
layout("OMG") 

// If you wanted to one of your classes 
case class AwesomeClass(i: Int, s: String) 

// Scala will infer that type `A` is `AwesomeClass` in this call 
layout(AwesomeClass(5, "omg"))