0

I have a class defined as below :

class VocabWord(cn1: Int = 0, word1: String = null)  {
   var cn = cn1
   var word = word1         
}

and also there exists an array as below :

var vocab = new Array[VocabWord](100)

Now, when I perform an operation like this below :

vocab = vocab.sortWith((x, y) => x.cn < y.cn) 

I am getting an null pointer exception.

1
  • 2
    please use CamelCase for class names. vocab_word is an eyesore, the convention is to write VocabWord. _ is already too far overloaded in Scala! Commented Feb 19, 2014 at 18:46

2 Answers 2

3

You are initializing the array with 100 null's

var vocab = new Array[VocabWord](100) // Array(null, null, null.....)

You can't apply the method cn to null

var vocab = Array[VocabWord](new VocabWord(100), new VocabWord(3))
vocab.sortWith( (x, y) => x.cn < y.cn)
// Array(VocabWord@49ac9ae3, VocabWord@21a4c98e)
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to create an array with new elements in, you can use Array.init:

val vocab = Array.fill[vocab_word](100)(new vocab_word)

at present you are creating an array containing 100 null references.

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.