Cory Klein
Cory Klein

Reputation: 55610

Implicit does not cause type to be converted when expected

package com.coryklein.lct.model

import org.scalatest.FlatSpec
import language.implicitConversions

class VertexTest extends FlatSpec {

  case class Vertex(x: Double, y: Double)

  implicit def tupleWrapper(tuple: (Double, Double)): Vertex =
    new Vertex(tuple._1, tuple._2)

  "A Vertex" should "be implicitly created from a tuple" in {
    val v: Vertex = (0, 0)
  }

}

In this code, the (0,0) doesn't get implicitly converted into a Vertex as I expect. Why?

Upvotes: 0

Views: 34

Answers (1)

Cory Klein
Cory Klein

Reputation: 55610

See your compiler error:

Error:(17, 21) type mismatch;  found   : (Int, Int)  required: VertexTest.this.Vertex
    val v: Vertex = (0, 0)
                    ^

The type of (0,0) is (Int,Int) which does not match the definition of the implicit you created which is (Double,Double), therefore your implicit cannot be applied.

To resolve your problem, change the types to match or define a new implicit conversion.

Upvotes: 3

Related Questions