转换为泛型的Scala问题
我试着写一些函数,根据输入类型做不同的事情。 例如,我这样做:转换为泛型的Scala问题,scala,generics,casting,Scala,Generics,Casting,我试着写一些函数,根据输入类型做不同的事情。 例如,我这样做: def Foo[T](inList: List[String]): ArrayBuffer[T] = { val out: ArrayBuffer[T] = new ArrayBuffer[T]() inList.map ( x => { val str = x.substring(1) out += str.asInstanceOf[T] }) out } 但是如果我用Foo[Long](新
def Foo[T](inList: List[String]): ArrayBuffer[T] = {
val out: ArrayBuffer[T] = new ArrayBuffer[T]()
inList.map ( x => {
val str = x.substring(1)
out += str.asInstanceOf[T]
})
out
}
但是如果我用
Foo[Long](新列表(“123”、“2342”)
调用这个函数,我会得到一个ArrayBuffer
和String
s,而不是Long
s。很抱歉我的noob问题,我想了解scala和泛型。将字符串
转换为长
不会使其变长,这是一个错误,因此您应该会收到一个运行时错误,说明您无法将字符串转换为长。因为T没有对它可以是什么设置任何限制,所以不能期望调用不在所有对象上的任何方法(toString
就是一个例子)。您可以自己提供该函数(这几乎是map的精确签名,因此您可以直接使用该函数):
或者确保对象的类型是您知道其上的方法的类型(使用类型绑定):
def Foo(inList: List[String]): (ArrayBuffer[Object]) = {
val out: ArrayBuffer[Object] = new ArrayBuffer[Object]()
inList.map ( x => {
val str=x.substring(1)
out += str.asInstanceOf[Object]
})
(out)
}
import scala.collection.mutable.ArrayBuffer
// here we define how convert string to longs
implicit def stringToLong(s: String) = s.toLong
// now this function requires to have converter from string to T in context
def Foo[T](inList: List[String])(implicit f: (String) => T): (ArrayBuffer[T]) = {
val out: ArrayBuffer[T] = new ArrayBuffer[T]()
inList.map { x =>
val str = x.substring(1)
out += f(str) // here we apply converter
}
out
}
// when function is called, appropriate implicit converter from context will be used
Foo[Long](List("51", "42"))
您是否在REPL中签出了代码?一切看起来都很好
scala.collection.mutable.ArrayBuffer[Long]=ArrayBuffer(23342)
不知道目标是什么,但强制转换正在破坏类型安全性。你的ArrayBuffer
对你没有多大帮助。为什么不返回列表上的映射结果(答案中提到了一个转换器函数)?
def Foo(inList: List[String]): (ArrayBuffer[Object]) = {
val out: ArrayBuffer[Object] = new ArrayBuffer[Object]()
inList.map ( x => {
val str=x.substring(1)
out += str.asInstanceOf[Object]
})
(out)
}
import scala.collection.mutable.ArrayBuffer
// here we define how convert string to longs
implicit def stringToLong(s: String) = s.toLong
// now this function requires to have converter from string to T in context
def Foo[T](inList: List[String])(implicit f: (String) => T): (ArrayBuffer[T]) = {
val out: ArrayBuffer[T] = new ArrayBuffer[T]()
inList.map { x =>
val str = x.substring(1)
out += f(str) // here we apply converter
}
out
}
// when function is called, appropriate implicit converter from context will be used
Foo[Long](List("51", "42"))