Scala: value :: is not a member of Int

I recently started using scala, and I can't do anything from error messages. For the following code, I get a message (using eclipse):

def helper: Int => List[Int] = x =>  x match  {
    case 2 => 2::1
    ...
}

I can fix this using List (2,1), but is it not the same as 2 :: 1? I have similar problems when the List (...) approach will be harder to use, so I really want to know where my thinking error is.

+4
source share
3 answers

Infix statements are interpreted as method calls in Scala. If infix statements end with a colon, this is a method call on the right operand with the left operand as its argument. Otherwise, it is a method call in the left operand with the correct operand as an argument.

, x + y, , x.+(y), .. + x, y - . x :: y , y.::(x), :: y.

, :: 1, Int. Int ::, , , , :: Int.

::, ( - , ::), 2 :: 1 :: Nil . List() .

+9

2::1 Scala :

{ val x = 2; 1.::(x) }

, :, -, op -, e1 op e2 { val x = e1; e2.op(x) } (. Scala , 6.12.3, . 84, . 92 PDF).

, ,

1.::(2)

1 Int, Int :: ( , ), , .

ayvango,

2::1::Nil

Nil.::(2).::(1)

, Nil List[Nothing] ::, . scala.collection.immutable.List , :: - List[Int], .::(1) .

-

2::List(1)

List(1).::(2) , .

, List(2,1) , 2::1, 2::1::Nil. , :

  • Nil -
  • if head - , tail - , head::tail -

( , )

sealed abstract class List[+A]
final case class ::[B](head: B, tl: List[B]) extends List[B]
object Nil extends List[Nothing]

, Nil ::.

Int List[Int], -

implicit def wrap(x : Int) : List[Int] = List(x)

, , Scalaz, , , .

+3

:: is the method defined in the list. You are trying to use this operator with type Int. Take a look at: http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List

As @ayvango pointed out, you can do:

def helper: Int => List[Int] = x =>  x match  {
  case 2 => 2 :: 1 :: Nil
}
+2
source

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


All Articles