Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accept multiple types for a parameter in scala

Tags:

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?

like image 852
Jason Wheeler Avatar asked Mar 07 '12 23:03

Jason Wheeler


People also ask

What is _ and _1 in Scala?

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.

How do you pass parameters to a Scala function?

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.

What is .type in Scala?

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.

What is variable argument fields in Scala?

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].


1 Answers

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

like image 191
blouerat Avatar answered Oct 19 '22 23:10

blouerat