logo       

Implicit type conversion: msg#00466

lang.scala

Subject: Implicit type conversion

I have found what appears to be an anomaly in implicit type coercion. I
have attempted to trivialise my example, but it is still 50 or so LOC. I
have annotated the code with the relevant question in the relevant place
in the code with comments. The problem is that this code will not
compile. I expect that the code will compile successfully, or fail to
compile with 2 errors, yet it seems to fail only with 1 error. That is
to say, a contradiction exists from my perspective and I'd appreciate
any explanation that clarifies this situation for me, thanks.

Search for:
"why does this compile..."
and
"...while this does not compile?"

sealed abstract class CList[+A]
case object Nil extends CList[Nothing]
final case class Cons[+A](head: A, tail: CList[A]) extends CList[A]

sealed abstract class TriState
final case object ON extends TriState
final case object OFF extends TriState
final case object NEUTRAL extends TriState

object CList {
implicit def string2CList(xs: String): CList[Char] = {
// todo
// inefficient, write imperative code
// go on, you can do it.
if(xs isEmpty)
Nil
else
Cons(xs charAt 0, xs substring 1)
}

implicit def cList2String (xs: CList[Char]): String = {
// todo
""
}
}

object TriState {
import CList._

implicit def list2TriState(xs: CList[Char]): TriState = {
if(xs == string2CList("1"))
ON
if(xs == string2CList("0"))
OFF
else
NEUTRAL
}
}

final case class X(ts: TriState) {

}

object Y {
import CList.string2CList
import TriState.list2TriState

def f1(): X = {
// why does this compile...
val x: CList[Char] = "x"
X(x)
}

def f2(): X = {
// ...while this does not compile?
// error: type mismatch;
// found : java.lang.String("x")
// required: TriState
X("x")
}
}

--
Tony Morris
http://tmorris.net/


Attachment: signature.asc
Description: OpenPGP digital signature

<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise