Abdul Rahman Abdul Rahman - 1 month ago 12
Scala Question

What is wrong with the following scala code

I am getting the following compile time error in the code below

Error:(7, 29) not found: value Cons

def ::[B >: A](head: B) = Cons[B](head, this)

package basics

sealed trait List[+A] {

import Types._

def ::[B >: A](head: B) = Cons[B](head, this)

def foreach(f: A => Unit): Unit = {
this match {
case x :: t => {
f(x)
t foreach f
}
case Nil => ()
}
}

}

object Types {
type Cons[A] = ::[A]
}
case class ::[+A](head: A, tail: List[A]) extends List[A]
object Nil extends List[Nothing]


object Application {

def main(args: Array[String]): Unit ={
println("hello")

3 :: Nil
}
}

Answer

Cons is a type alias not a value. It cannot occur on value position. For example:

I made a few modifications to your program to make it work:

case class ::[+A](head: A, tail: List[A]) extends List[A]
object Nil extends List[Nothing]

object Types {
  type Cons[A] = ::[A]
  def cons[A](head: A, tail: List[A]) = ::(head,tail)
}

sealed trait List[+A] {
  import Types._

  def ::[B >: A](head: B):Cons[B] = cons[B](head, this)
}

In def ::[B >: A](head: B):Cons[B] = cons[B](head, this), :Cons[B] illustrates one correct use case of a type alias.

Another problem with your program is the existence of two :: overloaded symbols in the same scope, that's why it required the creation of Types.cons, otherwise the Scala compiler thinks we are trying to invoke List#::

Here is a example from the REPL:

scala> 3 :: Nil
res0: Types.Cons[Int] = ::(3,Nil$@46fd71)

scala> 3 :: 4 :: Nil
res1: Types.Cons[Int] = ::(3,::(4,Nil$@46fd71))

See the type of the expressions is Cons[Int].

Comments