Reputation: 4502
I am testing out some code shown below that basically defines multiple implicit val
s taking a string as input and converting it to corresponding types.
The problem I have is that the conversions like toLong
, toDouble
and toInt
become unresolved for some reason.
class Parse[T](val f: String => T) extends (String => T) {
def apply(s: String): T = f(s)
}
object Parse {
def apply[T](f: String => T) = new Parse[T](f)
implicit val parseLong: Parse[Long] = Parse[Long](s => s.toLong)
implicit val parseDouble: Parse[Double] = Parse[Double](s => s.toDouble)
implicit val parseInt: Parse[Int] = Parse[Int](s => s.toInt)
}
What is wrong with this code?
Upvotes: 1
Views: 51
Reputation: 51683
The thing is that, since Parse
extends String => T
, implicits parseLong
, parseDouble
, parseInt
define not only instances of Parse
but also implicit conversions String => Long
, String => Double
, String => Int
. And since .toLong
, .toDouble
, .toInt
are extension methods, this creates ambiguities.
You can either remove extends (String => T)
or resolve extension methods manually:
object Parse {
def apply[T](f: String => T) = new Parse[T](f)
implicit val parseLong: Parse[Long] = Parse[Long](s => new StringOps(s).toLong)
implicit val parseDouble: Parse[Double] = Parse[Double](s => new StringOps(s).toDouble)
implicit val parseInt: Parse[Int] = Parse[Int](s => new StringOps(s).toInt)
}
Upvotes: 4