Scala中部分应用的函数和类型推断

时间:2013-02-23 04:55:54

标签: scala type-inference

我一直在试验部分应用的功能,并且发生了这样的事情。假设我们有这样的代码:

class Color(name:String) {
override def toString = name
}

class Point(x: Int, y:Int) {
override def toString:String = "("+x +"," + y + ")"
 }

class Linestyle(name: String) {
override def toString = name
 }

def drawLine(width:Double, color: Color, style: Linestyle, a:Point, b: Point): Unit = {
println("Draw " + width + " " + color + " " + style + " " + " line from point: " + a +  " to point " + b)
}

当我尝试创建drawSolidLine函数时,它只以这样的方式获取4个参数:

def drawSolidLine (c: Color, a:Point, b: Point):Unit =
drawLine(1.0, _:Color, new Linestyle("SOLID"), _:Point, _:Point)

并尝试将其称为

drawSolidLine(2.5, new Color("Black"),new Point(2,4), new Point(3,1))

我没有编译器错误,但调用什么也没有返回。

另一方面,当我以这种方式创建drawSolidLine时:

val drawSolidLine = drawLine(_:Double, _:Color, new Linestyle("SOLID"),
                            _:Point, _:Point)

之前调用它,我有所需的输出:

Draw 1.0 Black SOLID  line from point: (2,4) to point (3,1)

我缺少什么?

1 个答案:

答案 0 :(得分:3)

你正在做两件截然不同的事情。第一:

def drawSolidLine (c: Color, a:Point, b: Point):Unit =
  drawLine(1.0, _:Color, new Linestyle("SOLID"), _:Point, _:Point)

首先,请注意,您传递的参数均未被使用。表达式drawLine(1.0, _:Color, new Linestyle("SOLID"), _:Point, :Point)是一个函数,它不依赖于传递的参数,并且返回,除了返回类型为Unit。在这种情况下,该功能被丢弃。

第二

val drawSolidLine = drawLine(_:Double, _:Color, new Linestyle("SOLID"),
                             _:Point, _:Point)

首先,您可以将val替换为def,它的工作方式相同。 Val vs def不是问题

因此,drawSolidLine将会返回相同的函数,因为它的类型不是Unit。但是,这次(2.5, new Color("Black"),new Point(2,4), new Point(3,1))未传递给drawSolidLine,因为它不带参数。因此,它们将被传递给正在返回的函数,从而产生所需的效果。