DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Vulnerable Code [Comic]
  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client

Trending

  • Data Governance – Data Privacy and Security – Part 1
  • How To Remove Excel Worksheets Using APIs in Java
  • The Impact of AI and Platform Engineering on Cloud Native's Evolution: Automate Your Cloud Journey to Light Speed
  • A Java developer's guide to Quarkus
  1. DZone
  2. Coding
  3. Languages
  4. Duck Typing in Scala: Structural Typing.

Duck Typing in Scala: Structural Typing.

By 
Carlo Scarioni user avatar
Carlo Scarioni
·
Feb. 20, 13 · Interview
Like (2)
Save
Tweet
Share
41.0K Views

Join the DZone community and get the full member experience.

Join For Free

Scala offers a functionality known as Structural Types which allows to set a behaviour very similar to what dynamic languages allow to do when they support Duck Typing (http://en.wikipedia.org/wiki/Duck_typing)

The main difference is that it is a type safe, static typed implementation checked up at compile time. This means that you can create a function (or method) that receives an expected duck. But at compile time it would be checked that anything that is passed can actually quack like a Duck.

Here is an example. Let’s say we want to create a function that expects anything that can quack like a duck. This is how we would do it in Scala with Structural Typing:

def quacker(duck: {def quack(value: String): String}) {
  println (duck.quack("Quack"))
}

You can see that in the definition of the function we are not expecting a particular class or type. We are specifying an Structural Type which in this case means that we are expecting any type that has a method with the signature quack(string: String): String.

So all the following examples will work with that function:

object BigDuck {
  def quack(value: String) = {
    value.toUpperCase
  }
}

object SmallDuck {
  def quack(value: String) = {
    value.toLowerCase
  }
}

object IamNotReallyADuck {
  def quack(value: String) = {
    "prrrrrp"
  }
}

quacker(BigDuck)
quacker(SmallDuck)
quacker(IamNotReallyADuck)


You can see that there is no interface or anything being implemented by any of the three objects we have defined. They simply have to define the method quack in order to work in our function.

If you run the code above you get the output:

QUACK
quack
prrrrrp


If on the other hand you try to create an object without a quack method and try to call the function with that object you would get a compile error. For example trying to do this:

object NoQuaker {

}

quacker(NoQuaker)

You would get the error:

error: type mismatch; found : this.NoQuaker.type required: AnyRef{def quack(value: String): String} quacker(NoQuaker)

Also, you don’t even need to create a new type or class. You could use AnyRef to create an object with the quack method. Like this:

val x = new AnyRef {
  def quack(value: String) = {
    "No type needed "+ value
  }
}

and you can use that object to call the function:

quacker(x)

You can also specify in the function that expects the structural type, the the parameter object must respond to more than one method. Like this:

def quacker(duck: {def quack(value: String): String; def walk(): String}) {
  println (duck.quack("Quack"))
}

There you are saying that any object you pass to the function needs to respond to both methods quack and walk. This is also checked at compile time.

Under the covers the use of Structural Types in this way will be handled by reflection. This means that it is a more expensive operation than the standard method call. So use only when it actually makes sense to use it.



Duck typing Typing Scala (programming language)

Published at DZone with permission of Carlo Scarioni, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Vulnerable Code [Comic]
  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: