Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create empty Tuple or String in Scala?

Tags:

scala

I need return tuple , but if something goes wrong I want return empty tuple, like Seq.empty[Type] or Nil in Lists. Is it possible? Also I am curious about is it possible with String type.

like image 557
Azula Avatar asked Dec 19 '22 16:12

Azula


2 Answers

I want return empty tuple

That doesn't make sense. A tuple is not a collection. The idea of "emptiness" is simply non-sensical. The length of a tuple is part of its type. So, an empty tuple is a different type than a non-empty tuple.

In fact, it doesn't even make sense to talk about "tuple" as a type. There are pairs (2-tuples aka Tuple2), triples (3-tuples aka Tuple3), quadruples, quintuples, sixtuples, septuples, octuples, 9-tuples, 10-tuples, etc, and they are all different types.

Also, more or less the only sensible thing you can do with a tuple is to extract its elements. So, for a tuple with no elements, there is pretty much no sensible thing you can do. What use is a structure that holds no values and has no operations? It's completely useless.

In fact, a 0-tuple is isomorphic to the Unit value, the value which denotes the absence of a useful value. In Scala, and also Haskell, the syntax for an empty tuple is actually used for denoting the Unit value:

val u = ()
// => u: Unit = ()

Also I am curious about is it possible with String type.

Yes, of course, you can have an empty string:

val s = ""
// => s: String = ""
like image 100
Jörg W Mittag Avatar answered Dec 31 '22 02:12

Jörg W Mittag


Since you need to return an a value that can go wrong. In Scala the recommended way to deal with this is returning an Option, Try or Either value.

For instance:

def somethingThatCanGoWrongWithTry(): Try[(Int, String)] = {
  Try{
    val intValue = sideEffectValueInt()
    val stringValue = sideEffectValueString()
    (intValue, stringValue)
  }
}

def somethingThatCanGoWrongWithOption(): Option[(Int,String)] = {
  Try {
    val intValue = sideEffectValueInt()
    val stringValue = sideEffectValueString()
    (intValue, stringValue)
  }.toOption
}

def somethingThatCanGoWrongWithEither(): Either[Oops, (Int,String)] = {
  Try {
    val intValue = sideEffectValueInt()
    val stringValue = sideEffectValueString()
    (intValue, stringValue)
  } match {
    case Success(value) => Right(value)
    case Failure(exception) => Left(Oops(exception))
  }
}
like image 38
Jose Antonio Jimenez Saez Avatar answered Dec 31 '22 00:12

Jose Antonio Jimenez Saez