19.3. Using Duck Typing (Structural Types)
Problem
You’re used to “Duck Typing” (structural types) from another language like Python or Ruby, and want to use this feature in your Scala code.
Solution
Scala’s version of “Duck Typing” is known as using a
structural type. As an example of this approach,
the following code shows how a callSpeak
method can require that its obj
type parameter have a speak()
method:
def
callSpeak
[
A
<:
{
def
speak
()
:
Unit
}](
obj
:
A
)
{
// code here ...
obj
.
speak
()
}
Given that definition, an instance of any class that has a
speak()
method that takes no
parameters and returns nothing can be passed as a parameter to callSpeak
. For example, the following code
demonstrates how to invoke callSpeak
on both a Dog
and a Klingon
:
class
Dog
{
def
speak
()
{
println
(
"woof"
)
}
}
class
Klingon
{
def
speak
()
{
println
(
"Qapla!"
)
}
}
object
DuckTyping
extends
App
{
def
callSpeak
[
A
<:
{
def
speak
()
:
Unit
}](
obj
:
A
)
{
obj
.
speak
()
}
callSpeak
(
new
Dog
)
callSpeak
(
new
Klingon
)
}
Running this code prints the following output:
woof Qapla!
The class of the instance that’s passed in doesn’t matter at all.
The only requirement for the parameter obj
is that it’s an instance of a class that
has a speak()
method.
Discussion
The structural type syntax is necessary in this example because
the callSpeak
method invokes a
speak
method on the object that’s passed in. In a statically typed language, there must be some guarantee that the object that’s passed in will have this method, and this recipe shows ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.