d-_-b
d-_-b

Reputation: 4502

Cannot resolves symbol X, when defining multiple implicit vals

I am testing out some code shown below that basically defines multiple implicit vals 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

Answers (1)

Dmytro Mitin
Dmytro Mitin

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

Related Questions