logo       

Re: Implicit type conversion: msg#00471

lang.scala

Subject: Re: Implicit type conversion

Would you expect the code below to compile, because you expect the compiler to infer a transitive view f;g: A -> C from the existence of f: A->B and g:B->C ?

I don't see a view from String to TriState there, but I see two views from String to List[Char] and from List[Char] to Tristate.

Burak

On 1/29/07, Tony Morris <tmorris@xxxxxxxxxxx> wrote:
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/







--
Burak Emir
Research Assistant / PhD Candidate
Programming Methods Group
EPFL, 1015 Lausanne, Switzerland
http://lamp.epfl.ch/~emir
<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise