简体   繁体   English

提供类型不匹配错误Scala的方法中的调用方法

[英]Calling Method inside a method giving a type mismatch error Scala

So I'm trying to call a method("Mean") from inside another method("Centre"), it's giving a type mismatch error. 所以我试图从另一个方法(“中心”)内部调用一个方法(“均值”),它给出了类型不匹配的错误。

But if I execute the method("Mean") seperately and store it's result in some variable and then execute method("Centre") using the variable instead of method("Mean"), it works. 但是,如果我分别执行method(“ Mean”)并将结果存储在某个变量中,然后使用变量而不是method(“ Mean”)执行method(“ Centre”),则它会起作用。

Can anyone please explain why? 谁能解释为什么?

val X = Vector(3.0,4,5)
val Y = Vector(6,9.0,15)

type D = Double
type V = Vector[D]
def Mean (v:V)= v.sum/v.length
val meanX = Mean(X)
def Centre (v:V) = v.map(X => X - Mean(X))
Centre(X)

Error: 错误:

command-1723108043672149:8: error: type mismatch;
found   : D
(which expands to)  Double
required: V
(which expands to)  scala.collection.immutable.Vector[Double]
def Centre (v:V) = v.map(X => X - Mean(X))

but it works if I use "meanX" instead of "Mean(X): 但是,如果我使用“ meanX”而不是“ Mean(X),它就可以工作:

Centre: (v: V)scala.collection.immutable.Vector[Double]
res36: scala.collection.immutable.Vector[Double] = Vector(-1.0, 0.0,1.0)

Mean() is defined to take an argument of type V (ie Vector[Double] ) but in this code, v.map(X => X - Mean(X)) you're trying to pass a Double value instead, because you have redefined the variable X . Mean()定义为采用V类型的参数(即Vector[Double] ),但是在此代码v.map(X => X - Mean(X))您尝试传递Double值,因为您已经重新定义了变量X Thus the error. 因此错误。

I think what you want to do is v.map(n => n - Mean(X)) or, better yet, v.map(_ - Mean(X)) . 我认为您想做的是v.map(n => n - Mean(X))或者更好的是v.map(_ - Mean(X)) That way X has only one meaning. 这样, X仅具有一个含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM