Midiparse
Midiparse

Reputation: 4781

Is it possible in Scala to write an expression that placed in a function parameter, defaults the parameter value?

I have the following constructor

class Indexer(
  index: String,
  host: String,
  port: Int = DEFAULT_ES_PORT)

I only want to pass the port parameter if it isn't -1, otherwise I want to use the default value. My naive approach was:

val esi = new Indexer(
  index = es.index,
  host = es.getHost,
  port = if (es.getPort != -1) es.getPort
)

but on the 4th line i get a compiler error of course:

type mismatch; found : Unit required: Int Error occurred in an application involving default arguments.

because the else branch evaluates to Unit. Of course I could be writing this:

val esi = if (es.getPort != -1) {
    new Indexer(
      index = es.index,
      host = es.getHost,
      port = es.getPort
    ) 
  } else {
    new Indexer(
      index = es.index,
      host = es.getHost
    )
  }

But I wonder if there is a more concise way?

Upvotes: 1

Views: 60

Answers (2)

curious
curious

Reputation: 2928

I would Prefer Pattern Matching :

val esi = es.getPort match  {
      case -1 => new Indexer(es.index,es.getHost) 
      case x => new Indexer(es.index,es.getHost,x)
  }

Upvotes: 1

Gregor Raýman
Gregor Raýman

Reputation: 3081

The problem is that if (es.getPort != -1) es.getPort is missing the else clause, so that the resulting type of this expression is Unit.

You could solve by providing the else clause:

val esi = new Indexer(
  index = es.index,
  host = es.getHost,
  port = if (es.getPort != -1) es.getPort else DEFAULT_ES_PORT
)

This of course would mean that you need to use the DEFAULT_ES_PORT in your caller's code.

An alternative is to use for the parameter port the type Option[Int] and use None, if you want the default and convert it to an Int within the constructor of Indexer.

Upvotes: 1

Related Questions