Dmitry Reutov
Dmitry Reutov

Reputation: 3032

Scala: why type conversion implicit breaks the code

I have a simple code

private def convertFieldsNames (fieldsNames: Array[String]): Array[String] =
  fieldsNames.map(convertFieldName)

private def convertFieldName (fieldName: String): String = s"!!! $fieldName"

val res = convertFieldsNames(Array("123", "456"))
res.map(println)

it works fine, but when i add type conversions functions, which i'm gonna use in other functions

implicit def fromStringToEitherStringOrArray (str: String): Either[String, Array[String]] = Left(str)
implicit def fromArrayToEitherStringOrArray (arr: Array[String]): Either[String, Array[String]] = Right(arr)

i get an error in a line

fieldsNames.map(convertFieldName)

type mismatch;
 found   : String => String
 required: Array[String] => ?

i expected that these conversions will effect only if conversion to Either value is needed, so i cant get why this error bubbles up in a line where no Either type at all

Upvotes: 1

Views: 90

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51703

Just too many implicit conversions. Try

private def convertFieldsNames (fieldsNames: Array[String]): Array[String] =
  (fieldsNames: ArrayOps[String]).map(convertFieldName)

Compiler chose wrong conversion Array[String] => Either[String, Array[String]] rather than Array[String] => ArrayOps[String] because .map can be not only Array#map but also Either#map. And type inference/type checking works so that when there is type mismatch error it's too late to come back and choose proper implicit conversion.

Upvotes: 5

Related Questions