aJ8585
aJ8585

Reputation: 1

Scala List[Any] has a element as function. How to get return value?

I'm a novice in Scala and this moment I'm learning about it... I'm testing code and I have a list[Any] like this:

  var list: List[Any] = List(
    "a string",
    732, // an integer
    'c', // a character
    true, // a boolean value
    (x: String) => "String return " + x)

I want to get return value of index 4, but I obtain an error. I don't know how to get the return value.. that is my doubt.

var test = list(4);
test("hello") // Error

Upvotes: 0

Views: 117

Answers (2)

radumanolescu
radumanolescu

Reputation: 4161

You can call it like so:

scala> val f = (x: String) => "String return " + x
f: String => String = <function1>
scala> val y = f.asInstanceOf[ String => String ].apply("x")
y: String = String return x
scala> val y = f.asInstanceOf[ String => String ]("x")
y: String = String return x

Upvotes: 0

akuiper
akuiper

Reputation: 214927

You need to cast the function from Any to String => String before invoking it:

var test = list(4)

test.asInstanceOf[String => String]("hello")
// res21: String = String return hello

Or:

val test = list(4).asInstanceOf[String => String]
// test: String => String = <function1>

test("hello")
// res23: String = String return hello

Upvotes: 1

Related Questions