mosmic mosmic - 1 year ago 89
Scala Question

Using List[Char].head in Scala

New to Scala here. Trying to check with a function if the first character of a list matches.

def checkFistChar(chars: List[Char]): Boolean =
if (chars.head == "3") true
else false

In the line of the condition i get
Comparing unrelated types

checkFistChar("3 is larger than 2".toList)
returns false

Answer Source

The value "3" is a String because you are using double quotes, not a Char. You need to use single quotes instead. Also, you don't need the if/else:

def checkFirstChar(chars : List[Char]) = chars.head == '3'

One other problem with your function is that calling head on an empty list would throw an exception. In general you should only use headOption which returns an Option:

//empty list returns false
def safeCheckFirstChar(chars : List[Char]) : Boolean = 
    .map(_ == '3')

Which is equivalent to Tzach's & Chris' suggestions in the comments as well as pattern matching:

def safeCheckFirstChar2(chars : List[Char]) = 
    .exists(_ == '3')

def safeCheckFirstChar3(chars : List[Char]) =
  chars.headOption == Some('3')

def safeCheckFirstChar4(chars : List[Char]) = chars.headOption match {
  case Some('3') => true
  case _ => false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download