2016-09-27 118 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"))