AnAmuser
AnAmuser

Reputation: 1895

Use java methods as scala function

Can you do something like this were Java is a java library

class TryStuff(method:() => Any) {
   private val lib: Java = new Java

   val tryStuff:TryStuff = new TryStuff(lib.method)
}

Is there someway to convert lib.method to a scala object

Upvotes: 0

Views: 139

Answers (2)

Marco
Marco

Reputation: 1652

You do not need to do anything special. Java methods are ready to be invoked in the Scala code.

In your example any method that does not have parameters can be used, in this case I use the method exists() of class java.io.File:

import java.io.File

class TryStuff(method:() => Any) {
    private val lib: File = new File("a.file")
    val tryStuff:TryStuff = new TryStuff(lib.exists)
}

Upvotes: 0

Robin Green
Robin Green

Reputation: 33083

val tryStuff:TryStuff = new TryStuff(x => lib.method(x))

or more concisely

val tryStuff:TryStuff = new TryStuff(lib.method _)

Upvotes: 1

Related Questions