2

I have following code:

import java.io._
import com.twitter.chill.{Input, Output, ScalaKryoInstantiator}

import scala.reflect.ClassTag

object serializer {

  val instantiator = new ScalaKryoInstantiator
  instantiator.setRegistrationRequired(false)
  val kryo = instantiator.newKryo()

  def load[T](file:_=>_,name:String,cls:Class[T]):T = {
    if (java.nio.file.Files.notExists(new File(name).toPath())) {
      val temp = file
      val baos = new FileOutputStream(name)
      val output = new Output(baos, 4096)
      kryo.writeObject(output, temp)
      temp.asInstanceOf[T]
    }
    else {
      println("loading from " + name)
      val baos = new FileInputStream(name)
      val input = new Input(baos)
      kryo.readObject(input,cls)
    }
  }
}

I want to use it in this way:

val mylist = serializer.load((1 to 100000).toList,"allAdj.bin",classOf[List[Int]])

I don't want to run (1 to 100000).toList every time so I want to pass it to the serializer and then decide to compute it for the first time and serialize it for future or load it from file.

The problem is that the code block is running first in my code, how can I pass the code block without executing it?

P.S. Is there any scala tool that do the exact thing for me?

0

1 Answer 1

4

To have parameters not be evaluated before being passed, use pass-by-name, like this:

def method(param: =>ParamType)

Whatever you pass won't be evaluated at the time you pass, but will be evaluated each time you use param, which might not be what you want either. To have it be evaluated only the first time you use, do this:

def method(param: =>ParamType) = {
  lazy val p: ParamType = param

Then use only p on the body. The first time p is used, param will be evaluated and the value will be stored. All other uses of p will use the stored value.

Note that this happens every time you invoke method. That is, if you call method twice, it won't use the "stored" value of p -- it will evaluate it again on first use. If you want to "pre-compute" something, then perhaps you'd be better off with a class instead?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.