Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 从多态局部函数内的多态封闭函数访问参数_Scala - Fatal编程技术网

Scala 从多态局部函数内的多态封闭函数访问参数

Scala 从多态局部函数内的多态封闭函数访问参数,scala,Scala,我试图使函数多态,但遇到了以下问题 以下函数编译: libraryDependencies += "org.spire-math" %% "spire" % "0.10.1" import spire.math._ import spire.implicits._ def foo(a : Int, b : Int) : Int = { def bar(c : Int, d :Int) : Int = { c * b } a * bar(1,2)

我试图使函数多态,但遇到了以下问题

以下函数编译:

libraryDependencies += "org.spire-math" %% "spire" % "0.10.1"

import spire.math._
import spire.implicits._

  def foo(a : Int, b : Int) : Int = {

    def bar(c : Int, d :Int) : Int = {
      c * b
    }
    a * bar(1,2)
  }
这里的基本思想是局部函数,能够在局部函数中引用封闭函数的参数。但是,如果我尝试使此函数具有多态性,如下所示:

import spire.math._
import spire.implicits._

  def foo[A:Numeric] (a : A, b : A) : A = {

    def bar[A:Numeric](c : A, d :A) : A = {
      c * b
    }
    a * bar(1,2)
  }

:22:错误:重载的方法值*带有可选项:
(rhs:Double)(隐式ev1:spire.代数.字段[A(在方法栏中)])A(在方法栏中)
(rhs:Int)(隐式ev1:spire.代数.环[A(在方法栏中)])A(在方法栏中)
(rhs:A(在方法栏中))A(在方法栏中)
无法应用于(A(在方法foo中))
c*b
^

我遇到了一个问题,编译器无法解析
bar
函数中的乘法运算符。有多种隐含的替代方案。如何解决此问题?

无需将
条形图作为通用:

import spire.math._
import spire.implicits._

def foo[A: Numeric] (a: A, b: A) : A = {
  def bar(c: A, d: A) : A = {
    c * b
  }
  a * bar(1, 2)
}
不过,您只得到了一个错误,因为您编写了
c*b
(而
bar
的第二个参数名为
d
),这意味着您试图将外部
A
和内部泛型
A
相乘,而没有提供任何证据证明它们相关

import spire.math._
import spire.implicits._

def foo[A: Numeric] (a: A, b: A) : A = {
  def bar(c: A, d: A) : A = {
    c * b
  }
  a * bar(1, 2)
}