Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion from String to Int in scala 2.8

Is there something I've got wrong with the following fragment:-

object Imp {
  implicit def string2Int(s: String): Int = s.toInt

  def f(i: Int) = i

  def main(args: Array[String]) {
    val n: Int = f("666")
  }
}

I get the following from the 2.8 compiler:-

Information:Compilation completed with 1 error and 0 warnings
Information:1 error
Information:0 warnings
...\scala-2.8-tests\src\Imp.scala
Error:Error:line (4)error: type mismatch;
found : String
required: ?{val toInt: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method string2Int in object Imp of type (s: String)Int
and method augmentString in object Predef of type (x:String)scala.collection.immutable.StringOps
are possible conversion functions from String to ?{val toInt: ?}
implicit def string2Int(s: String): Int = s.toInt

like image 750
Don Mackenzie Avatar asked Nov 12 '09 23:11

Don Mackenzie


People also ask

How do I convert a string to an int in Scala?

A string can be converted to integer in Scala using the toInt method. This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException. So, the statement: val i = "Hello".

What is an implicit conversion function in Scala?

Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another. Implicit conversions are applied in two conditions: First, if an expression of type A and S does not match to the expected expression type B.

What is the implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

What is Scala toInt?

Scala Char toInt() method with example The toInt() method is utilized to convert a stated character into an integer or its ASCII value of type Int.


1 Answers

What is happening is that Java does not define a toInt method on String. In Scala, what defines that method is the class StringOps (Scala 2.8) or RichString (Scala 2.7).

On the other hand, there is a method toInt available on Int as well (through another implicit, perhaps?), so the compiler doesn't know if it is to convert the string to StringOps, through the defined implicit, or to Int, through your own implicit.

To solve it, call the implicit explicitly.

object Imp {
  implicit def string2Int(s: String): Int = augmentString(s).toInt

  def f(i: Int) = i

  def main(args: Array[String]) {
    val n: Int = f("666")
  }
}
like image 112
Daniel C. Sobral Avatar answered Oct 19 '22 02:10

Daniel C. Sobral