Scala String.endsWith
Check the end of a filename when listing receipts saved as PDFs.
A simple example
String.endsWith
- Start with "abc" and "bc"
- Do this Compare the ending
- Result Yes
object Lesson {
def main(args: Array[String]): Unit = {
val value = "abc"
val other = "bc"
println(if (value.endsWith(other)) "yes" else "no")
}
}
yes
Syntax
label.endsWith(".pdf")
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonFind filenames with a receipt extension
A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.
object Lesson {
def main(args: Array[String]): Unit = {
val label = "receipt.pdf"
println(if (label.endsWith(".pdf")) "yes" else "no")
}
}
yes
The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.
Find a class roster
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "class.csv"
val other = ".csv"
println(if (value.endsWith(other)) "yes" else "no")
}
}
yes
The final characters match the requested extension.
Exclude a backup export
A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "class.csv.old"
val other = ".csv"
println(if (value.endsWith(other)) "yes" else "no")
}
}
no
The final extension is .old.
What to watch for
A filename suffix describes a naming convention. It cannot verify the contents of a file.