Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Call function only with specified path-dependent type param

Lets have a class A with inner class.

class A {
    class InnerA
}

And class Test that holds instance of A

class Test(inst: A) {
    def someFun(p: inst.InnerA) {} //Neither A#InnerA, Nor inst.type#InnerA
}

Now i need to restrict someFun to be called only with parameter of type InnerA of specified inst (member of Test). (Not by any instance of InnerA that is achieved with A#InnerA)

val a: A = new A
val inna: a.InnerA = new a.InnerA
val test: Test = new Test(a)

But when i write this code:

test.someFun(inna)

type checker warns that "Type mismatch, expected: inst.type#InnerA, actual: a.InnerA"

Please suggest how can it be done.


Similar but NOT suitable solution is of form

def fun(a: A)(p: a.InnerA) {}

As for application: An A class is Enumeration class, and InnerA is Enumeration.Value class. And Test is a class i'd like to restrict to use with only specified Enumeration. And "inna" are instances of enumeration values that are constructed inside the Enumeration subclass.

like image 588
Markus Marvell Avatar asked Dec 03 '25 01:12

Markus Marvell


1 Answers

With new Test(a) you lose the information that a becomes test.inst. For example, the following works:

class Test(val inst: A) {
  def someFun(p: inst.InnerA) = ()
}

val test: Test = new Test(new A)
val inna = new test.inst.InnerA
test.someFun(inna)
like image 52
0__ Avatar answered Dec 05 '25 20:12

0__



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!