Last active
September 24, 2020 17:45
-
-
Save oreillyross/2f83ba30c75596bff10f to your computer and use it in GitHub Desktop.
Common mistakes made in scala coding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val a = 1 //> a : Int = 1 | |
val b = 2 //> b : Int = 2 | |
// Common mistakes with pattern matching | |
// the lower case variable pattern needs backwards quotes to work. | |
def oneOrTwo(i: Int): String = i match { | |
case `a` => "One!" | |
case `b` => "Two!" | |
} //> oneOrTwo: (i: Int)String | |
oneOrTwo(2) //> res0: String = Two! | |
// Common mistakes with type inference - folds return type inferred from default or starting type | |
// The list.empty needs to specifically type [A] | |
def reverse[A](list: List[A]): List[A] = { | |
list.foldLeft(List.empty[A]) { | |
(acc, elem) => elem :: acc | |
} | |
} //> reverse: [A](list: List[A])List[A] | |
def myreverse[A] = (_: List[A])./:(List.empty[A])(_.::(_)) | |
reverse(List(1, 2, 3)) //> res1: List[Int] = List(3, 2, 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment