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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Build Your Own Programming Language
  • How Consistency and Continuity Shape Professional Coding Careers
  • 10 Tips To Improve Python Coding Skills in 2024
  • Code Review That Matters: Tips and Best Practices

Trending

  • Modern Python: Patterns, Features, and Strategies for Writing Efficient Code (Part 1)
  • Securing Cloud Infrastructure: Leveraging Key Management Technologies
  • Debugging Streams With Peek
  • Using My New Raspberry Pi To Run an Existing GitHub Action
  1. DZone
  2. Coding
  3. Languages
  4. The Pitfall of Implicit Returns

The Pitfall of Implicit Returns

Implicit returns are a feature in some languages, but beware, concise code doesn't necessarily imply being better code. Learn more!

By 
Nicolas Fränkel user avatar
Nicolas Fränkel
DZone Core CORE ·
Mar. 26, 24 · Analysis
Like (1)
Save
Tweet
Share
601 Views

Join the DZone community and get the full member experience.

Join For Free

Implicit returns are a feature in some languages. They have recently bitten me, so here's my opinion.

Statements, Expressions, and Returns

Before diving into implicit returns, we must explain two programming concepts influencing them. A lot of literature is available on the subject, so I'll paraphrase one of the existing definitions:

An expression usually refers to a piece of code that can be evaluated to a value. In most programming languages, there are typically three different types of expressions: arithmetic, character, and logical.

A statement refers to a piece of code that executes a specific instruction or tells the computer to complete a task.

— Expression vs. Statement

Here's a Kotlin snippet:

Kotlin
 
val y = 10                //1
val x = 2                 //1

x + y                     //2

println(x)                //1


  1. Statement, executes the assignment "task"
  2. Expression, evaluates to a value, e.g., 12

Functions may or may not return a value. When they do, they use the return keyword in most programming languages. It's a statement that needs an expression.

In Kotlin, it translates to the following:

Kotlin
 
fun hello(who: String): String {
    return "Hello $who"
}


In this regard, Kotlin is similar to other programming languages with C-like syntax.

Implicit Returns

A couple of programming languages add the idea of implicit returns: Kotlin, Rust, Scala, and Ruby are the ones I know about; each has different quirks.

I'm most familiar with Kotlin: you can omit the return keyword when you switch the syntax from a block body to an expression body. With the latter, you can rewrite the above code as the following:

Kotlin
 
fun hello(who: String): String = "Hello $who"


Rust also allows implicit returns with a slightly different syntax.

Rust
 
fn hello(who: &str) -> String {
    return "Hello ".to_owned() + who;          //1
}

fn hello_implicit(who: &str) -> String {
    "Hello ".to_owned() + who                  //2
}


  1. Explicit return
  2. Transform the statement in expression by removing the trailing semicolon — implicit return

Let's continue with Kotlin. The expression doesn't need to be a one-liner. You can use more complex expressions:

Kotlin
 
fun hello(who: String?): String =
    if (who == null) "Hello world"
    else "Hello $who"


The Pitfall

I was writing code lately, and I produced something akin to this snippet:

Kotlin
 
enum class Constant {
    Foo, Bar, Baz
}


fun oops(constant: Constant): String = when (constant) {
    Constant.Foo -> "Foo"
    else -> {
        if (constant == Constant.Bar) "Bar"
        "Baz"
    }
}


Can you spot the bug?

Let's use the function to make it clear:

Kotlin
 
fun main() {
    println(oops(Constant.Foo))
    println(oops(Constant.Bar))
    println(oops(Constant.Baz))
}


The results are:

Foo
Baz
Baz


The explanation is relatively straightforward. if (constant == Constant.Bar) "Bar" does nothing. The following line evaluates to "Bar"; it implicitly returns the expression. To fix the bug, we need to add an else to transform the block into an expression:

Kotlin
 
if (constant == Constant.Bar) "Bar"
else "Baz"


Note that for simpler expressions, the compiler is smart enough to abort with an error:

Kotlin
 
fun oops(constant: Constant): String =
    if (constant == Constant.Bar) "Bar"      //1
    "Baz"


  1. 'if' must have both main and 'else' branches if used as an expression

Conclusion

Implicit return is a powerful syntactic sugar that allows for more concise code. However, concise code doesn't necessarily imply being better code. I firmly believe that explicit code is more maintainable in most situations.

In this case, I was tricked by my code!

Beware of implicit returns.

Go Further

  • Expression vs. Statement
  • Rust, Ruby, and the Art of Implicit Returns
  • To be clear, Rust does not have "implicit returns"
  • On the merits of verbosity and the flaws of expressiveness
Kotlin (programming language) Syntax (programming languages) Coding (social sciences)

Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build Your Own Programming Language
  • How Consistency and Continuity Shape Professional Coding Careers
  • 10 Tips To Improve Python Coding Skills in 2024
  • Code Review That Matters: Tips and Best Practices

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: