Scala函数语法
我目前正在使用教程学习Scala,遇到了一个我不理解的语法(我还没有找到答案): 在 我不理解布局之后和参数声明之前的[A] 是退货类型吗 对我来说,scala中函数的一般语法如下:Scala函数语法,scala,function,Scala,Function,我目前正在使用教程学习Scala,遇到了一个我不理解的语法(我还没有找到答案): 在 我不理解布局之后和参数声明之前的[A] 是退货类型吗 对我来说,scala中函数的一般语法如下: def functionName ([list of parameters]) : [return type] = { function body return [expr] } A是一种类型参数。类型参数允许您为任何a编写方法。可能是A是Int,Double,甚至是您编写的自定义类。因为所有这些都有
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
A
是一种类型参数。类型参数允许您为任何a
编写方法。可能是A
是Int
,Double
,甚至是您编写的自定义类。因为所有这些都有一个继承自Any
的toString
方法,所以这将起作用
例如,当我们这样做时:
println(layout(1L))
println(layout(1f))
这与写作相同:
println(layout[Long](1L))
println(layout[Float](1f))
其中显式传递了类型参数
def layout[A](x: A) = "[" + x.toString() + "]"
这是类型参数。此函数定义允许您提供任何类型作为此类型参数的参数
// 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"))
还有。。。在该方法中,指定函数参数x
为类型A
,Scala可以使用此信息从函数参数x
推断类型参数
因此,在使用该方法时,实际上不需要提供类型参数
,因此可以像下面这样以不太冗长的方式编写上述代码
// 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"))
我在下面绘制这个图表是为了概括常量、变量和函数的语法
如果您了解Java,这大致相当于他们使用
注释泛型方法的方式。不过,在这种情况下,它是否有用?为什么不干脆def布局(x:Any)
?@Thilo在这个特定的示例中,它没有太大的意义。人们可以使用任何来实现同样的目标。当一个人编写一个接受类型参数的方法时,通常会有可重用的代码,在编译时保留类型信息可以获得这些代码。@Thilo使用类型参数,可以在更复杂的场景中添加类型边界。
// 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"))
// 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"))