https://kotlinlang.org logo
#announcements
Title
# announcements
f

frank

08/21/2020, 4:43 AM
[Solved] I'm testing
java.nio
in Kotlin and I have a question: Why don't work
member references
to function is this case? *I know that with
Files.isDirectory(it)
work i*t
Copy code
val stream = Files.list(folder) 
val files  = stream.filter {  it != null && Files::isDirectory } // error in Files::isDirectory
                   .map    { it!! }
Error Msg:
Type mismatch.
Required: Boolean
Found: KFunction2<Path!, Array<(out) LinkOption!>!, Boolean>
PD: Sorry, if this topic doesn't have to be in this channel, but I didn't find JVM channel.
j

jbnizet

08/21/2020, 5:43 AM
Because in an expression
a && b
, both
a
and
b
must be booleans.
it != null
is a boolean expression, but
Files::isDirectory
is not: it’s a function reference.
You could pass such a function reference to
filter
, because that’s what it expects, but that’s not what you’re doing. I.e.
fileStream.filter(Files::isDirectory)
would be corrrect.
f

frank

08/21/2020, 6:05 AM
fileStream.filter(Files::isDirectory) would be corrrect.
@jbnizet , Work it this but I can't obtain
it
in the scope of
filter()
function if I add Predicate inside of filter I can obtain
it
but fail
Files::isDirectory
.
Copy code
val stream = Files.list(folder)
val files =  stream.filter(Files::isDirectory)//I cant obtain it
                    map   { it!! }.toList() 
//Files::isDirectory fail in predicate
files =  stream.filter(Predicate { it != null && Files::isDirectory  })
                               .map    { it!! }.toList()
j

jbnizet

08/21/2020, 6:08 AM
Well, you’re still trying to combine, with
&&
, a boolean and a function.
Files::isDirectory
is not a boolean. It’s a function which returns a boolean. To get a boolean, you need to call the function:
it != null && Files.isDirectory(it)
. When using
stream.filter(Files::isDirectory)
, it’s correct because filter expects a function which takes a Path and returns a boolean as argument, and Files::isDirectory is such a function.
Note that testing if a file returned by Files.list() is null is useless: this methods returns instances of Path. Why would there be a null in there?
f

frank

08/21/2020, 6:21 AM
Files.list() returns me Stream<Path!> and Path! means Path or Path?
j

jbnizet

08/21/2020, 6:25 AM
Yes. So you need to then read the documentation of the method (and think about what that function does), to know if there is a chance to have a null in that stream. Why would a method that returns the files in a directory would add nulls into that list?
👍 1
f

frank

08/21/2020, 6:30 AM
@jbnizet Ok, Thx for you help. I checked it
3 Views