Is it better to use import scala.reflect.io.File or java.io.File in Scala?

后端 未结 3 1242
渐次进展
渐次进展 2020-12-20 16:22

I see the scala.reflect.io.File class, is this supposed to help with file operations? Am I supposed to prefer to use this rather than java.io.File? What is the purpose of th

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 16:38

    Neither, you're supposed to use java.nio.file, of course.

    If you want to "enhance" that API with fancy operators, use extension methods. The author of that code has said as much on the mailing list. Being stuck on Java 6 is considered unfortunate.

    The package you're pointing to was pulled into the scala-reflect.jar to support reflection, but warnings are everywhere about its unsupported status.

    The AbstractFile abstraction is used by Position, which has a source file. The "file" you get from that is a java.io.File, but AbstractFile has factory methods that take the reflect.io.Path abstraction (with File and Directory subtypes). So all that code remains packaged together.

    I have to stop and think every time AbstractFile and File cross my path (pun alert). I used to have a purple "AbstractFile is, like, totally different from File" t-shirt, but it wore out with multiple washings.

    On the back it said, "Position has nothing to do with io.Position."

    Here is the warning as it touches api.Position, where of course it is user-facing in the scaladoc; notice it says it is a "Java file":

      /** Java file corresponding to the source file of this position.
       *
       *  The return type is `scala.reflect.io.AbstractFile`, which belongs to an experimental part of Scala reflection.
       *  It should not be used unless you know what you are doing. In subsequent releases, this API will be refined
       *  and exposed as a part of scala.reflect.api.
       *
       *  @group Common
       */
      def source: scala.reflect.internal.util.SourceFile
    

    To answer your first question, I think it's safe to say, Yes, it was supposed to help.

提交回复
热议问题