In Scala, how can I limit several parameters, should there be a type inside the same type?

I am trying to use a type dependent type with generics.

I have two classes, the class C2 is nested in C1.

case class C1(v1: Int) {
  case class C2(v2: Int)
}

And I have two objects of class C1 here:

object O1 extends C1(1)
object O2 extends C1(2)

I want to write a method that takes several parameters of type C2. And all these parameters must belong to the same C1 object.

For instance:

foo(O1.C2(10), O1.C2(11)) // all the C2 is inside the same O1
foo(O1.C2(10), O2.C2(20)) // not good, will not compile

I tried several ways to write such a method, but no one works.

The first:

def print1(p1: C1#C2, p2: C1#C2): Unit = {
  println(p1.v2, p2.v2)
}
print1(O1.C2(1111), O2.C2(2222)) // Not requited that p1 & p2 should have the same object of C1

Second:

def print2(p1: O1.C2, p2: O1.C2): Unit = {
  println(p1.v2, p2.v2)
}
print2(O1.C2(1111), O1.C2(1111)) // Can only accept the C2 inside O1

Third:

def print3[T <: C1#C2](p1: T, p2: T): Unit = {
  println(p1.v2, p2.v2)
}
print3(O1.C2(1111), O2.C2(2222)) // The same as the first one.

Last:

//  def print2[U <: C1](p1: U.C2, p2: U.C2): Unit = {
//    println(p1.v2, p2.v2)
//  }
// Not compile, Error: not found: value U

Anyway, can I archive this?

+4
source share
1 answer

You can do this, but you also need to pass the object itself:

def print(o: C1)(p1: o.C2, p2: o.C2) = ...

print(O1)(O1.C2(1111), O2.C2(2222))
+7
source

Source: https://habr.com/ru/post/1664242/


All Articles