I have two objects, ObjectA and ObjectB, both with a method update(). I want to write a function that accepts either ObjectA or ObjectB (but no other types). Conceptually, this is what I am trying to do:
def doSomething[T <: ObjectA | T <: ObjectB](obj: T) = {
obj.update
}
I realize there are other ways to solve this problem (eg, structural typing of the update() method, common base class, etc) but my question is it is possible to do it this way in Scala and if so what is the syntax? And what is this called?
Given the following definition − val t = (4,3,2,1) To access elements of a tuple t, you can use method t. _1 to access the first element, t. _2 to access the second, and so on.
Scala - Functions with Named Arguments Named arguments allow you to pass arguments to a function in a different order. The syntax is simply that each argument is preceded by a parameter name and an equals sign. Try the following program, it is a simple example to show the functions with named arguments.
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.
Scala - Function with Variable Arguments This allows clients to pass variable length argument lists to the function. Here, the type of args inside the print Strings function, which is declared as type "String*" is actually Array[String].
In Scala, there is the type Either to make a disjoint union. Basically, you will do something like:
def doSomething(obj: Either[ObjectA, ObjectB]) {
obj.fold(fa, fb)
}
Checkout http://www.scala-lang.org/api/current/scala/Either.html
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