Scala способ сделать Apache Commons Lang3 Подтвердить?

1

Что такое способ Scala выполнить то же самое, что и apache commons lang3 Подтвердить? т.е. валидация, предназначенная для проверки правильности ввода пользователя, в отличие от ошибок кодирования с помощью утверждений, в которых отказ от условия приведет к исключению 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;
}
  • 0
    Является ли org.apache.commons.lang3.Validate(path.exists(), "Illegal input path '" + path.getAbsolutePath() + "', it doesn't exist") даже допустимым? Какой метод вы вызываете? Во всяком случае, вопрос неясен. Вы пытаетесь позвонить в Common-validate? Или вы пытаетесь написать собственную подобную функцию проверки в Scala?
  • 0
    Просмотр документов, которые вы связали с конструктором для Validate , описывается как «Этот класс обычно не должен создаваться для экземпляров» ... и он не принимает никаких параметров. Таким образом, @vptheron правильно просит уточнить, какой метод вы вызываете, поскольку то, что у вас есть, не является методом в классе org.apache.commons.lang3.Validate которым вы связались.
Показать ещё 2 комментария
Теги:

1 ответ

0
Лучший ответ

По совпадению я только выяснил, что 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
}
  • 0
    Это OT, я не спрашивал в своем OP, является ли создание исключения ужасной идеей или нет, я спросил, что будет заменой Apache Commons Validate в Scala. Этот пример является просто примером проверки пользовательского ввода.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню