Compare types in Scala

I have two objects, each with locally defined types, and I want to determine if the types are the same. For example, I would like this code to compile:

trait Bar { type MyType } object Bar { def compareTypes(left: Bar, right: Bar): Boolean = (left.MyType == right.MyType) } 

However, the compilation failed with "MyType is not a member of Bar."

What's happening? Is there any way to do this?

+4
source share
1 answer

You can do this, but this requires a little extra hardware:

 trait Bar { type MyType } object Bar { def compareTypes[L <: Bar, R <: Bar](left: L, right: R)( implicit ev: L#MyType =:= R#MyType = null ) = ev != null } 

Now, if we have the following:

 val intBar1 = new Bar { type MyType = Int } val intBar2 = new Bar { type MyType = Int } val strBar1 = new Bar { type MyType = String } 

It works as expected:

 scala> Bar.compareTypes(intBar1, strBar1) res0: Boolean = false scala> Bar.compareTypes(intBar1, intBar2) res1: Boolean = true 

The trick is to ask for implicit evidence that L#MyType and R#MyType same, and provide a default value ( null ) if this is not the case. Then you can simply check if you get the default value or not.

+9
source

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


All Articles