Scala: A function to copy text to the system clipboard and get it from the system clipboard (copy and paste text)

When using Scala (or Java, Kotlin, or other JVM languages), and (a) you want to put a String on the system clipboard and/or (b) get a String off the system clipboard — i.e., copying and pasting text strings — I just used these functions, and can confirm that they work:

import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.awt.datatransfer.DataFlavor

def putStringOnClipboard(text: String): Unit =
    val stringSelection = new StringSelection(text)
    val clipboard = Toolkit.getDefaultToolkit.getSystemClipboard
    clipboard.setContents(stringSelection, null)

def getStringFromClipboard: Option[String] =
    try
        val clipboard = Toolkit.getDefaultToolkit.getSystemClipboard
        val contents = clipboard.getContents(null)
        if contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor) then
            Some(contents.getTransferData(DataFlavor.stringFlavor).asInstanceOf[String])
        else
            None
    catch
        case e: Exception =>
            System.err.println("Error getting string from clipboard: " + e.getMessage)
            None

You put a String on the system clipboard like this:

putStringOnClipboard(""Hello, clipboard world")

and you get a String off the system clipboard like this:

val clipboardText = getStringFromClipboard
clipboardText match
    case Some(text) => println(s"Clipboard contains: $text")
    case None       => println("Yikes! Clipboard does not contain a string or is empty")

As shown, this allows you to copy text to the system clipboard and then paste text from the system clipboard using JVM languages like Scala, Java, Kotlin, and others.

A key to this solution is that I only intend for these to work with text — i.e., the String data type. If you want it to work with other data types that may be on the system clipboard, you’ll have to handle that differently (and I’m leaving that as an exercise for the reader).