How to make the compiler check that 2 arguments of a method are of the same type?

Maybe I am missing something fundamental here, but I was reviewing some things in my code, and halfway through I noticed that my code is compiling where I expect it to not. So here is the method signature:

def checkUiFieldValue[T](fieldName:String, uiValue:T, expectedValue:T):Unit ={...}

Here is the place where it is used:

checkUiFieldValue("State", stateInListView(ar.name), ar.state)

The return type stateInListViewis the class ARState, and the type ar.stateis String. So the question is, why does it compile and does not tell me that the types do not match? I caught myself thinking that I expect the compiler to verify that uiValuethey expectedValueare of the same type T, but probably my guess is wrong.

Or Tdoes the type parameter in the method definition actually mean that both arguments will be passed in Anyin my case? If so, how should I properly restrict both arguments to the same type at compile time?

+4
source share
2 answers

One possible approach is to deduce the types of the two arguments separately, then use =:=to prove that they are the same:

def test2[S, T](a: String, b: S, c: T)(implicit ev: S =:= T): T = ???
val x = test2("", new A, new A) // compiles
val y = test2("", new A, new B) // doesn't compile; can't prove A =:= B

This may be a little strict for you, although with subtyping:

class C extends B
val z = test2("", new B, new C) // doesn't compile; can't prove B =:= C
val w = test2[B, B]("", new B, new C) // does compile
+4
source

As you noticed, the reason for compiling is what Tis the first common type between stateInListView(ar.name)and ar.state.

You can verify this by doing the following lines:

class A()
class B()

def test[T](a : String, b : T, c : T) : T = ???   

val x : Any = test("ciao", new A(), new B()) // Compiles OK
val y : A = test[A]("ciao", new A(), new B()) // Does not compile: B does not work
val z : B = test[B]("ciao", new A(), new B()) // Does not compile: A does not work

T (, test[A](...)), ....

+3

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


All Articles