Initiialize an empty tuple scala - string

I want to create a mutable tuple in scala (String, Set[String]).
And before I want to initialize it to an empty value first before adding to it
the set can not be initialized to empty set. The same for String.
I'm getting an error saying class java.lang.String is not a value
Is there a simple way to do that ? and What am I doing wrong

Empty Set can be defined like so
Set.empty[String] // because assert(Set.empty[String].isEmpty)
Empty String can be defined like so
"" // because assert("".isEmpty)
Empty tuple is not something Scala models as TupleN, I think. Instead it uses Unit type for it. Perhaps you are after something like so
val ta: (String, Set[String]) = ("", Set.empty)
val tb: (Option[String], Option[Set[String]]) = (None, None)
val tc: Option[(String, Set[String])] = None
The error message
class java.lang.String is not a value
means you are using a type where value is expected, for example, consider the difference between
Set[String] // ok
Set(String) // error

Related

Groovy: Plucking values out of a Map and into a Set

Groovy here. I have a class Fizz:
#Canonical
class Fizz {
Integer id
String name
}
In my program, I compose a map of them by their integral id field:
// Here, each key of the map corresponds to the Fizz#id of its value
// example:
// allFizzes[1] = new Fizz(1, 'Foobar')
// allFizzes[3004] = new Fizz(3004, 'Wakka wakka')
Map<Integer,Fizz> allFizzes = getSomehow()
I would know like to obtain a set of "bad" Fizzes whose name equals the string 'Sampson'. My best attempt:
Set<Fizz> badFizzes = allFizzes.find { k,v -> v.equals('Sampson') }
However this gives me runtime errors:
Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '24={
"id": 24,
"name": "Sampson"
},
' with class 'java.util.LinkedHashMap$Entry' to class 'java.util.Set'
So it looks like even though I'm specifying v.equals('Sampson') that Groovy is strill trying to save a Map key,value pair into a Set. What's the Grooviest solution here?
You'll want to use findAll (which returns a Collection) in place of find (which returns an Object). findAll applies the passed in closure to each EntrySet in the Map and returns a new collection with elements that satisfied your closure's criteria. You can then call values() on this newly returned collection.
Map<String, Integer> myMap = ["fizzStrength":29, "fizzQuality": 123, "fizzFizziness":3]
Set<Integer> found = myMap.findAll { k,v -> v > 4 }.values() // returns [29, 123]

Expression of Type Scala.Predef.String doesn't conform to expected type String

I have a function, validateCell, that takes a function, func, as one of its input parameters. It is as follows:
def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
cell match {
case Some(cellContents) => (func(cellContents), s"$cellContents is not valid.")
case None => (false, s"$cellKey, not found.")
}
}
I call the function as follows:
val map = Map("Well" -> "A110")
validateCell("Well", map.get("Well"), BarcodeWell.isValidWell)
The function that is passed in this case is as follows, though I don't think it's related to the problem:
def isValidWell(w: String): Boolean = {
val row: String = w.replaceAll("[^A-Za-z]", "")
val col: Int = w.replaceAll("[^0-9]+", "").toInt
isValidRow(row) && isValidColumn(col)
}
I am expecting validateCell to return a Tuple(Boolean, String), but I get the following error:
Error:(5, 55) type mismatch;
found : java.lang.String
required: String(in method validateCell)
case Some(cellContents) => (func(cellContents), s"$cellContents is not valid.")
I can make this error go away by converting the java strings in each tuple that are returned by the case statements to Scala strings like so:
s"$cellContents is not valid.".asInstanceOf[String]
s"$cellKey, not found.".asInstanceOf[String]
This seems really silly. What am I missing here? Shouldn't this conversion be handled by Scala automatically and why are my strings being cast as Java strings in the first place?
There is no difference between Scala strings and Java strings. In fact, Predef.String aliases to java.lang.String. However, you're working with neither of these things; you're working with a type parameter.
def validateCell[String](cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {
This is a generic function which takes a type argument whose name is String. When you call validateCell, this type argument is being inferred and filled in for you, by something that definitely isn't a string. My guess is that you're misunderstanding the point of the brackets and that you meant to write
def validateCell(cellKey: String, cell: Option[String], func:(String) => Boolean): Tuple2[Boolean, String] = {

Map Method sql.row extraction - data type error in Spark

I have a .sql.Row type RDD.
I am using the map method to unpack from the row and create a new RDD.
This question builds directly from what I learnt in Scala RDD String manipulation.
In the original RDD, vertices_raw I have a field Metrics that I use map on.
val vertices = vertices_raw.rdd.map(row=> (row.getAs[String]("Metrics").map(_.stripPrefix("name").toLong))
Resulting in:
error: value stripPrefix is not a member of Char
The same goes for .drop method for removing name.
I have tried adding a toString in attempt to convert from Char to String with no change.
val vertices = vertices_raw.rdd.map(row=> (row.getAs[String]("Metrics").toString.map(_.stripPrefix("name").toLong))
Instead of getAs[String] I also tried getString.
val vertices = vertices_raw.rdd.map(row=> (row.getString("Metrics").map(_.stripPrefix("name").toLong))
error: type mismatch;
found : String("toid")
required: Int
My practical question is how do I convert from Char to String? before performing the map function?
My fundamental question is what exactly does getAs[String] mean if it doesn't literally mean get and in String format? I have a misunderstood this clearly.
You are performing a map on a string - that is going to map over each char of the string. If you just want to call stripPrefix then just do that without the map.
row.getAs[String]("Metrics").stripPrefix("name").toLong

lazy instantiation of the map value

Is there a way to instantiate the value of map lazy?
For example
class MapTest {
#Lazy(soft = true) HashMap<String, List<String>> map
}
Doing like this I can use this call and get null without recieving NullPointerException
new MapTest().map.key1
However attempt to call
map.key1.remove(1)
will lead to NullPointerException due the value being null. (it would be fine if it threw IndexOutOfBounds exception)
Is there a way to instantiate the list value of the map?
try map.withDefault :
def map = [:].withDefault { [] }
assert map.key1.isEmpty()
Some explanation :
[:] is the groovy way to instantiate an empty hash map
withDefault is a groovy method on a map wich take a closure. this closure is call every time a key is requested to initialize the value if it doesn't exist. this closure take one parameter (the key) and should the value
[] is the groovy way to create an empty list - { [] } is a closure wich return an empty list for every key
see others examples here

String method to change particular element in Scala

I need to write a method in Scala that overrides the toString method. I wrote it but I also have to check that if there is an element that is '1' I will change it to 'a', else write the list as it is with the string method. Any suggestions how this can be done?
What error are you getting? seems to work for me
val l = List(1, 2, 3)
println(this)
override def toString(): String = {
val t = l.map({
case 1 => "a"
case x => x
})
t.toString
}
getting List(a, 2, 3) printed out
I see from the comments on your question that list is a List[List[Int]].
Look at the beginning of your code:
list.map { case 1 => 'a'; case x => x}
map expects a function that takes an element of list as a parameter - a List[Int], in your case. But your code works directly on Int.
With this information, it appears that the error you get is entirely correct: you declared a method that expects an Int, but you pass a List[Int] to it, which is indeed a type mismatch.
Try this:
list.map {_.map { case 1 => 'a'; case x => x}}
This way, the function you defined to transform 1 to a and leave everything else alone is applied to list's sublists, and this type-checks: you're applying a function that expects an Int to an Int.

Resources