Simple type inference in Scala

I looked at type inference in Scala, and there are a few things that I would like to understand a little better, why expression types / return methods must be explicitly declared in several cases.

Explicit Declaration return

Example (works if the keyword is returnomitted):

def upCase(s: String) = {
  if (s.length == 0)
    return s    // COMPILE ERROR - forces return type of upCase to be declared.
  else
    s.toUpperCase()
}

Why can't I use an explicitly typed parameter as a return value without declaring the return type? And this is not only for references to direct parameters, just for any expression such as "output".

Method overload

Example (cannot compile when the second method is added joiner):

def joiner(ss: List[String], sep: String) = ss.mkString(sep)

def joiner(ss: List[String]) = joiner(strings, " ")   // COMPILE ERROR WHEN ADDED
+3
source share
5 answers

, : , . 6.20 scala. , . , , , , .

EDIT:

, :

def bar() = {   
  if(guard())  
    return "SS"  
  else if(gurard1())  
    return true   
  2  
}

? , , , Any . , =)

+3

. .

"return" . , , " ". - , , . , , , .

, :

def toNumber(s: String) = {
  if (s == null)
    return ""

  if (s matches """\d+""")
    s.toInt
  else
    0
}

if . return if , .

+2

, , , .

, :

def upCase(s: String) = {
 if (s.length == 0)
   s    // note: no return
 else
   s.toUpperCase()
}

, .

+1

- ,

Scala /:

scala> def foo(s : String) = s + " Hello"
foo: (String)java.lang.String

scala> var t = foo("World")
t: java.lang.String = World Hello

scala> def bar( s : String) = s.toInt
bar: (String)Int

scala> var i = bar("3")
i: Int = 3

:

scala> var j = if (System.getProperty("user.name") == "oxbow") 4 else "5".toInt
j: Int = 5

EDIT. , return , : return - . joiner - . , , . , , , .

0

I suspect that the method of overloading (absence) of output is associated with a similar problem with recursive calls, because if overloaded methods do not call each other, it works fine:

  def joiner1(ss: List[String], sep: String) = ss.mkString(sep)
  def joiner(ss: List[String], sep: String) = ss.mkString(sep)
  def joiner(ss: List[String]) = joiner1(ss, " ")  

There are two overloaded joiner methods, but types are deduced correctly, the code is compiled.

0
source

Source: https://habr.com/ru/post/1719488/


All Articles