簡體   English   中英

Scala如何做apache commons lang3驗證?

[英]Scala way to do apache commons lang3 Validate?

與Apache Commons lang3 Validate相同的Scala方法是什么? 即,驗證針對用戶輸入驗證,而不是通過斷言導致錯誤的條件,斷言將導致IllegalArgumentException,例如

/**
 * Returns the newly created file only if the user entered a valid path.
 * @param path input path where to store the new file
 * @param fileName name of the file to be created in directory path
 * @throws IllegalArgumentException when the input path doesn't exist.  
 */
public File createFile(File path, String fileName) {
    // make sure that the path exists before creating the file
    // TODO: is there a way to do this in Scala without the need for 3rd party libraries
    org.apache.commons.lang3.Validate.isTrue(path.exists(), "Illegal input path '" + path.getAbsolutePath() + "', it doesn't exist")
    // now it is safe to create the file ...
    File result = new File(path, fileName)
    // ...
    return result;
}

碰巧的是,我剛剛發現require是Scala中的選擇方法,例如

/**
 * Returns the newly created file only if the user entered a valid path.
 * @param path input path where to store the new file
 * @param fileName name of the file to be created in directory path
 * @throws IllegalArgumentException when the input path doesn't exist.  
 */
def createFile(path: File, fileName: String) : File = {
    require(path.exists, s"""Illegal input path "${path.getAbsolutePath()}", it doesn't exist""")
    // now it is safe to create the file ...
    val result = new File(path, fileName)
    // ...
    result
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM