I have two objects, each with locally defined types, and I want to determine if the types are the same. For example, I'd like this code to compile:
trait Bar {
type MyType
}
object Bar {
def compareTypes(left: Bar, right: Bar): Boolean = (left.MyType == right.MyType)
}
However, compilation fails with "value MyType is not a member of Bar".
What's going on? Is there a way to do this?
String Comparison Using the == Method Here, the == method checks for the equality of stringOne and stringTwo and returns true. The above code prints a Boolean value false. Internally, the == method checks for null values first and then calls the equals() method of the first String object to check for their equality.
Scala String matches() method with exampleThe matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Return Type: It returns true if the string matches the regular expression else it returns false.
Type declaration is a Scala feature that enables us to declare our own types. In this short tutorial, we'll learn how to do type declaration in Scala using the type keyword. First, we'll learn to use it as a type alias. Then, we'll learn to declare an abstract type member and implement it.
You can do this, but it takes a little extra machinery:
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
are the same, and to provide a default value (null
) if they aren't. Then you can just check whether you get the default value or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With