Return type mismatch error for a tuple


Early days part 2. So I defined a Map for customer details as shown below:
scala> val customers = Map(1 -> (1, “A”, “S”), 2->(2, “P”, “S”))
_ customers: scala.collection.immutable.Map[Int,(Int, String, String)] = Map(1 -> (1,A,S), 2 -> (2,P,S))_

The following function I defined works fine.
scala> def getCust(x: Int, cust: Map[Int, (Int, String, String)]) = {
_ | println(cust.get(x)) }_
_ getCust: (x: Int, cust: Map[Int,(Int, String, String)])Unit_

_ scala> getCust(1, customers)_
_ Some((1,A,S))_

Then I try to redefine it by wanting to return a tuple from the function, I hit compile error which I tried to figure out to no avail. Any help is appreciated.

_scala> def getCust(x: Int, cust: Map[Int, (Int, String, String)]):(Int, String, String) = {_
_     | cust.get(x) }_
_<console>:12: error: type mismatch;_
_ found   : Option[(Int, String, String)]_
_ required: (Int, String, String)_
_       cust.get(x) }_
_               ^_



Map[A, B].get(key: A) returns Option[B] (None if key is not present)
Map[A, B].apply(key: A) returns B (exception if key is not present)

.apply can be abbreviated so second syntax is usually replaced by:
Map[A, B](key: A) which returns B


I have seriously no clue what you just said wrt the problem. Again, this is my first week with Scala. So I may not be knowing what you are trying to imply. I do know about apply method but I do not see how it is a problem of mismatch.



I’ve mainly rephrased what documentation says. You wanted to return a raw tuple, but Map.get returns value wrapped in Option (to support missing values).

Documentation for Map.get:[V]
Documentation for Map.apply:

If you want to know about .apply method and syntactic sugar for it, check this:

If you want to return raw value you should use .apply method instead of .get


Thanks. That helped.



Hi Anoop, btw you will make it easier to read your code samples if you format them properly. For block-level code samples (one or more lines), put three backtick characters before and after each block of code, like this (except use backtick, the key just below the Esc key):

def f(x: Int): Int = x + 1


Thanks Yawaramin. Will surely check it out and use it.

Thanks and Regards,
(20 words limit)