作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有人可以快速解释一下为什么在这种情况下隐式转换不起作用吗?谢谢。
scala> implicit def strTwoInt (s: String):Int = s.toCharArray.map{_.asDigit}.sum
strTwoInt: (s: String)Int
scala> List[Int]("1","2","3") sum
res3: Int = 6
scala> List("1","2","3") sum
<console>:9: error: could not find implicit value for parameter num: Numeric[java.lang.String]
List("1","2","3") sum
scala> val a = List("1","2","3")
scala> a.foldLeft(0)((i:Int, j:Int) => i+j)
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: (Int, java.lang.String) => Int
最佳答案
您的隐式转换将一个String转换为一个Int。在您的第一个示例中,它是由您尝试将字符串放入一个整数列表而触发的。
在第二个示例中,您有一个字符串列表,然后调用方法sum,该方法采用一个隐式Numeric[String]
。您的转换不适用,因为您既未尝试将String传递给编译器期望Int的位置,也未尝试调用Int而不是String中定义的方法。在这种情况下,您可以定义一个明确使用您的转换的Numeric[String]
,或者使用一个将List[Int]
作为参数的方法(向编译器提供提示):
scala> def sumIt( xs: List[Int] ) = xs sum
sumIt: (xs: List[Int])Int
scala> sumIt( List("1","2","3") )
res5: Int = 6
(Int,String) => Int
(Int,Int) => Int
a.foldLeft(0)((i:Int, j:String) => i+j)
Numeric[String]
的方法:
implicit object StringNumeric extends math.Numeric[String] {
val num = math.Numeric.IntIsIntegral
def plus(x: String, y: String) = num.plus(x,y).toString
def minus(x: String, y: String) = num.minus(x,y).toString
def times(x: String, y: String) = num.times(x,y).toString
def negate(x: String): String = num.negate(x).toString
def fromInt(x: Int) = x.toString
def toInt(x: String) = x
def toLong(x: String) = toInt(x)
def toFloat(x: String) = toInt(x)
def toDouble(x: String) = toInt(x)
def compare(x:String,y:String) = num.compare(x,y)
}
scala> List("1","2","3") sum
res1: java.lang.String = 6
关于scala - 为什么隐式转换在列表中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729196/
我是一名优秀的程序员,十分优秀!