Sunday, February 24, 2013

Scala Inferring Nothing

A lot of times i've run an issue with scala inference and type parameters:
abstract class Activity[T] {
  def apply (): T
}

object Count extends Activity[Int] {
  def apply (): Int = ...
}
// a method that needs to know both A and T
def run [T, A <: Activity[T]] (activity: A) = ...

Trying to use the method:
run(Count)
Produces:
error: inferred type arguments [Nothing,Count.type] do not conform to method run's type parameter bounds [T,A <: Activity[T]]

But it works if you pass the type parameters explicitly:
run[Int,Activity[Int]](Count)
A solution:
def run [T, A <: Activity[T]] (activity: A with Activity[T]) = ...

The rule seems to be that the compiler will usually infer only the parameters that appear directly in the parameter list.



2 comments:

  1. It is a good explanation. I am also encontering an error similar to this . Since a newbee to scala, I couldnt Figure out whats happening. Can you give me some methods to solve this problem. The error is as follows

    [error] /home/spark/Desktop/intern/spark-0.6.1/bagel/src/main/scala/spark/bagel/examples/GraphGeneration.scala:54: inferred type arguments [String,GraphGenVertex,GraphGenMessage] do not conform to method run's type parameter bounds [K,V <: spark.bagel.Vertex,M <: spark.bagel.Message[K]]
    [error] val result = Bagel.run(sc,verts,emptyMsgs,2)(compute)
    [error] ^
    [error] one error found
    [error] {file:/home/spark/Desktop/intern/spark-0.6.1/}bagel/compile:compile: Compilation failed

    ReplyDelete
  2. Its hard without seeing the code, but are you sure that GraphGenMessage is a subtype of Message[String]?
    Can you show me the definition of "run"?

    ReplyDelete