Omid
Omid

Reputation: 1989

Scala: providing type information for function argument in coding time

Here is a simplified version of the problem that I have:

case class HEdge[N,E](n:N, e:E)
case class ANode[N,E](head:N ,out:List[HEdge[N,E]])
object ANode{
  def apply[N,E](head:N ,out:HEdge[N,E]*):ANode[N,E] = ANode(head,out.toList)
}

When I want to use it with simple types it works as expected:

val x = ANode[String,String]("aaa", HEdge("bb","cc"))

I also test it with another more complicated type:

case class Foo[N](e:N => Boolean)
case class Bar[E](e:E => Boolean)

it works when I fully specify the type parameters for functions inside the Foo and Bar:

val y1 = ANode[Foo[String], Bar[String]](Foo[String](x => x == ""), HEdge(Foo[String](x => x == ""), Bar[String](z => z == "")))

but it doesn't work when I leave it to compiler to find the types:

val y = ANode[Foo[String], Bar[String]](Foo(x => x == ""), HEdge(Foo(x => x == ""), Bar(z => z == "")))

How can I force the compiler to work properly ?

Upvotes: 0

Views: 56

Answers (1)

Victor Moroz
Victor Moroz

Reputation: 9225

case class ANode[N,E](head:N ,out:List[HEdge[N,E]]) defines it's own apply which you overload and it causes ambiguity. This will compile:

case class HEdge[N,E](n:N, e:E)
class ANode[N,E](head:N ,out:List[HEdge[N,E]])
object ANode{
  def apply[N,E](head:N ,out:HEdge[N,E]*):ANode[N,E] = new ANode(head,out.toList)
}
case class Foo[N](e:N => Boolean)
case class Bar[E](e:E => Boolean)
val y1 = ANode[Foo[String], Bar[String]](Foo(x => x == ""), HEdge(Foo(x => x == ""), Bar(z => z == "")))

Upvotes: 4

Related Questions